Language Features
Wrapper Classes
Complete lesson for Wrapper Classes using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Wrapper Classes
Section: Language Features. Java wrapper classes — all eight wrappers, autoboxing and unboxing, conversions between String, primitive and wrapper, built-in methods, the Integer cache, and the classic null and == traps.
What are wrapper classes?
- A wrapper class is a class whose object holds one primitive value. It "wraps" an
int,double,char, and so on inside an object. - Java has eight primitive types and eight matching wrapper classes in
java.lang(so no import is needed). - All wrapper classes are
final(cannot be extended) and immutable (the value inside never changes). - Real-life analogy: a gift box. The primitive is the gift; the wrapper is the box that lets you put it on a shelf (a collection), label it, or leave the box empty (
null).
public class WrapperIntro {
public static void main(String[] args) {
int marks = 90; // primitive: just a value
Integer boxedMarks = marks; // wrapper object holding 90
System.out.println(boxedMarks); // 90
System.out.println(boxedMarks.getClass()); // class java.lang.Integer
System.out.println(boxedMarks.doubleValue()); // 90.0 (methods available)
}
} Why we need wrapper classes
- Collections and generics work only with objects: you write
List<Integer>, neverList<int>. - A wrapper can be
null, which is useful for "no value yet" (for example an optional database column or a missing map entry). - Wrappers provide utility methods and constants:
Integer.parseInt,Integer.MAX_VALUE,Character.isDigit,Double.isNaN. - APIs that accept
Object(reflection,equals,Object[], serialization) need reference types. - Frameworks such as JPA / Hibernate, Jackson, and Spring use wrapper types for nullable fields and form inputs.
Primitive types and their wrapper classes
- Two names differ from the primitive:
intbecomesIntegerandcharbecomesCharacter. The rest just capitalize the first letter. Voidis a ninth placeholder class that represents thevoidkeyword (used in reflection andCallable<Void>).
| Primitive | Wrapper class | Size | Default (primitive field) | Default (wrapper field) | Range constants |
|---|---|---|---|---|---|
byte | Byte | 8 bits | 0 | null | Byte.MIN_VALUE = -128, Byte.MAX_VALUE = 127 |
short | Short | 16 bits | 0 | null | -32768 to 32767 |
int | Integer | 32 bits | 0 | null | -2147483648 to 2147483647 |
long | Long | 64 bits | 0L | null | about -9.22 x 10^18 to 9.22 x 10^18 |
float | Float | 32 bits | 0.0f | null | Float.MAX_VALUE = 3.4028235E38 |
double | Double | 64 bits | 0.0 | null | Double.MAX_VALUE = 1.7976931348623157E308 |
char | Character | 16 bits | NUL character (code 0) | null | 0 to 65535 (UTF-16 code unit) |
boolean | Boolean | JVM dependent | false | null | Boolean.TRUE, Boolean.FALSE |
Wrapper class hierarchy
- The six numeric wrappers extend the abstract class
java.lang.Number, which providesintValue(),longValue(),doubleValue(), and friends. CharacterandBooleanextendObjectdirectly, because they are not numbers.- Every wrapper implements
Comparable(so they sort naturally) andSerializable. - Because of
Number, you can write one methoddouble total(List<? extends Number> list)that sums integers, longs, and doubles.
java.lang.Object
├── java.lang.Number(abstract)
│ ├── Byte
│ ├── Short
│ ├── Integer
│ ├── Long
│ ├── Float
│ └── Double
├── java.lang.Character
└── java.lang.Boolean Autoboxing and unboxing
- Autoboxing (Java 5+): the compiler converts a primitive to its wrapper automatically.
Integer x = 5;becomesInteger x = Integer.valueOf(5);. - Unboxing: the compiler converts a wrapper back to a primitive.
int y = x;becomesint y = x.intValue();. - It is pure compiler work; the bytecode still calls
valueOfandintValue.
| Where it happens | Example | What the compiler inserts |
|---|---|---|
| Assignment | Integer a = 10; | Integer.valueOf(10) |
| Method argument | list.add(25); | list.add(Integer.valueOf(25)) |
| Return value | Integer f() { return 7; } | return Integer.valueOf(7); |
| Arithmetic | Integer c = a + b; | Integer.valueOf(a.intValue() + b.intValue()) |
| Comparison with primitive | if (a > 5) | a.intValue() > 5 |
| Increment | a++; | a = Integer.valueOf(a.intValue() + 1); (new object) |
| Enhanced for loop | for (int n : list) | n = it.next().intValue() |
import java.util.ArrayList;
import java.util.List;
public class BoxingDemo {
public static void main(String[] args) {
Integer boxed = 42; // autoboxing
int raw = boxed; // unboxing
List<Integer> scores = new ArrayList<>();
scores.add(75); // autoboxing into the list
scores.add(90);
int total = 0;
for (int s : scores) total += s; // unboxing in the loop
System.out.println(raw + " " + total); // 42 165
}
} Ways to create wrapper objects
| Way | Example | Returns | Notes |
|---|---|---|---|
| Autoboxing | Integer a = 100; | Integer | Simplest; uses valueOf internally (cache applies) |
valueOf(primitive) | Integer.valueOf(100) | Integer | Recommended explicit way; uses the cache |
valueOf(String) | Integer.valueOf("100") | Integer | Parses text; throws NumberFormatException on bad input |
parseXxx(String) | Integer.parseInt("100") | int (primitive) | Use when you need the primitive |
| Constructor | new Integer(100) | Integer | Deprecated since Java 9, marked for removal since Java 16; always a new object |
Conversions between String, primitive, and wrapper
| From | To | Method | Example |
|---|---|---|---|
| String | primitive | Xxx.parseXxx(s) | int n = Integer.parseInt("25"); |
| String | wrapper | Xxx.valueOf(s) | Double d = Double.valueOf("3.5"); |
| primitive | wrapper | Xxx.valueOf(p) or autoboxing | Long l = Long.valueOf(9L); |
| wrapper | primitive | xxxValue() or unboxing | int n = boxed.intValue(); |
| primitive | String | String.valueOf(p) or Xxx.toString(p) | String s = String.valueOf(42); |
| wrapper | String | obj.toString() | String s = boxed.toString(); |
| wrapper | other primitive | Number methods | double d = boxed.doubleValue(); |
| String (other base) | int | parseInt(s, radix) | Integer.parseInt("ff", 16) = 255 |
| int | binary / hex / octal String | toBinaryString, toHexString, toOctalString | Integer.toBinaryString(10) = 1010 |
| char | int digit | Character.getNumericValue(c) | Digit character 7 gives 7 |
public class Conversions {
public static void main(String[] args) {
int age = Integer.parseInt("21"); // String -> int
Double price = Double.valueOf("499.99"); // String -> Double
Integer boxed = Integer.valueOf(age); // int -> Integer
long big = boxed.longValue(); // Integer -> long
String text = String.valueOf(age); // int -> String
System.out.println(age + 1); // 22
System.out.println(price * 2); // 999.98
System.out.println(big + text); // 2121
System.out.println(Integer.parseInt("1010", 2)); // 10
System.out.println(Integer.toHexString(255)); // ff
}
} Common Integer methods and constants
Long,Short, andBytehave the same method names with their own types (Long.parseLong,Short.parseShort, ...).
| Method / constant | Type | Purpose | Example result |
|---|---|---|---|
Integer.parseInt(s) | static | String to int | parseInt("42") = 42 |
Integer.parseInt(s, radix) | static | Parse in another base | parseInt("777", 8) = 511 |
Integer.valueOf(x) | static | int or String to Integer (cached) | valueOf("7") = 7 |
Integer.toString(i) | static | int to String | "42" |
Integer.toBinaryString(i) | static | Binary text | toBinaryString(5) = 101 |
Integer.toHexString(i) | static | Hex text | toHexString(255) = ff |
Integer.toOctalString(i) | static | Octal text | toOctalString(8) = 10 |
Integer.compare(a, b) | static | Negative, zero, or positive | compare(3, 7) = -1 |
Integer.max(a, b) / min / sum | static | Handy as method references | Integer::sum in reduce |
Integer.bitCount(i) | static | Number of 1 bits | bitCount(7) = 3 |
Integer.reverse(i) | static | Reverse the bit order | Used in bit puzzles |
Integer.signum(i) | static | Sign as -1, 0, or 1 | signum(-9) = -1 |
Integer.decode(s) | static | Parse with prefix 0x, #, or 0 | decode("0x1F") = 31 |
intValue(), longValue(), doubleValue() | instance | Unwrap to a primitive | boxed.doubleValue() |
equals(obj) | instance | Value equality (same type only) | a.equals(b) |
compareTo(other) | instance | Natural ordering | a.compareTo(b) |
hashCode() | instance | Returns the int value itself | Integer.valueOf(5).hashCode() = 5 |
Integer.MAX_VALUE / MIN_VALUE | constant | Largest / smallest int | 2147483647 / -2147483648 |
Integer.SIZE / BYTES | constant | Bits / bytes in an int | 32 / 4 |
Common Character methods
- All of these are
staticand take achar(or an int code point).
| Method | Purpose | Typical use |
|---|---|---|
Character.isDigit(ch) | Is it 0-9 (or another Unicode digit)? | Validate a PIN or phone number |
Character.isLetter(ch) | Is it a letter? | Validate a name |
Character.isLetterOrDigit(ch) | Letter or digit? | Username rules |
Character.isAlphabetic(cp) | Alphabetic, including more Unicode scripts | International text |
Character.isUpperCase(ch) / isLowerCase(ch) | Check case | Password strength checks |
Character.isWhitespace(ch) | Space, tab, newline, ... | Word counting |
Character.toUpperCase(ch) / toLowerCase(ch) | Change case | Case-insensitive compare |
Character.getNumericValue(ch) | Digit character to its int value | Sum of digits from a String |
Character.toString(ch) / String.valueOf(ch) | char to String | Building text |
Character.compare(a, b) | Compare two chars | Sorting |
Common Double, Float, and Boolean methods
| Method / constant | Purpose | Note |
|---|---|---|
Double.parseDouble(s) | String to double | Accepts "1e3", "NaN", "Infinity" |
Double.valueOf(s) | String to Double | No cache for Double / Float |
Double.isNaN(d) | Is it Not-a-Number? | d == Double.NaN is always false; use this |
Double.isInfinite(d) / isFinite(d) | Check for infinity | 1.0 / 0 is Infinity, not an exception |
Double.compare(a, b) | Safe compare | Handles NaN and -0.0 consistently |
Double.MAX_VALUE | Largest double | About 1.8 x 10^308 |
Double.MIN_VALUE | Smallest positive double | 4.9E-324, not the most negative value |
Float.parseFloat(s) | String to float | Same family of methods as Double |
Boolean.parseBoolean(s) | String to boolean | true only for "true" in any case; anything else (even null) is false |
Boolean.valueOf(b) | Returns Boolean.TRUE or Boolean.FALSE | Never creates new objects |
Boolean.logicalAnd / logicalOr / logicalXor | Boolean operators as methods | Useful in reduce |
Boolean.getBoolean(name) | Reads a system property | Trap: it does not parse the string |
The wrapper cache (Integer cache)
- Autoboxing and
valueOfreuse pre-created objects for small values, so==may seem to work for them and then fail for bigger values. Integer a = 100, b = 100;givesa == btrue.Integer c = 200, d = 200;givesc == dfalse. Always compare values withequalsor unbox first.- The Integer cache upper bound can be raised with
-XX:AutoBoxCacheMax=<size>, but code must never depend on it.
| Wrapper | Cached values | Effect of == for cached values |
|---|---|---|
Byte | All values (-128 to 127) | Always the same object |
Short | -128 to 127 | Same object only inside the range |
Integer | -128 to 127 (upper bound configurable) | Same object only inside the range |
Long | -128 to 127 | Same object only inside the range |
Character | 0 to 127 (ASCII) | Same object only for ASCII |
Boolean | TRUE and FALSE | Always the same two objects |
Float / Double | No cache | Every boxing creates a new object |
public class CacheDemo {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b); // true (cached object)
System.out.println(c == d); // false (two objects)
System.out.println(c.equals(d)); // true (value comparison)
System.out.println(c.intValue() == d.intValue()); // true
}
} Differences between primitive types and wrapper classes
| Point | Primitive (int) | Wrapper (Integer) |
|---|---|---|
| What it is | Raw value | Object holding a value |
| Stored in | Stack (locals) or inside the owning object | Heap object; variable holds a reference |
| Memory | 4 bytes for int | About 16 bytes object plus a 4 to 8 byte reference |
| Can be null? | No | Yes |
| Default as a field | 0 | null |
| Use in generics / collections | Not allowed | Required (List<Integer>) |
| Methods | None | intValue(), compareTo(), equals(), statics like parseInt |
| Comparing with == | Compares values | Compares references (use equals) |
| Speed | Fastest | Slower: allocation, indirection, GC |
| Typical use | Loops, math, counters | Collections, nullable fields, APIs needing objects |
Advanced — Wrapper Classes
Null unboxing and NullPointerException
- Unboxing calls
intValue()behind the scenes, so unboxingnullthrowsNullPointerException. - Common sources:
Map.getfor a missing key, a nullable database column, or a JSON field that was absent. - Fix: check for null, use
getOrDefault,Objects.requireNonNullElse, or keep the value as a wrapper until you know it is present.
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class NullUnboxing {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 10);
// int n = stock.get("book"); // NullPointerException
int n1 = stock.getOrDefault("book", 0); // 0
Integer maybe = stock.get("book");
int n2 = Objects.requireNonNullElse(maybe, 0); // 0 (Java 9+)
System.out.println(n1 + n2);
}
} The ternary operator unboxing trap
- If one branch of
?:is a wrapper and the other is a primitive, the whole expression becomes the primitive type. - So the wrapper branch is unboxed, and if it is
nullyou get aNullPointerExceptioneven though you assign to a wrapper. - Fix: make both branches wrappers (
Integer.valueOf(0)) or use anifstatement.
public class TernaryTrap {
public static void main(String[] args) {
Integer cached = null;
boolean useCache = true;
// Integer bad = useCache ? cached : 0; // NPE: type is int, cached is unboxed
Integer ok = useCache ? cached : Integer.valueOf(0); // null, no exception
System.out.println(ok);
}
} Overloading with boxing: widening beats boxing beats varargs
- When choosing an overload, the compiler tries three phases in order: exact match or widening, then boxing / unboxing, then varargs.
- So
m(5)prefersm(long)(widening) overm(Integer)(boxing), andm(Integer)overm(int...). - Widening then boxing is not allowed: an
intcannot become aLong.
public class OverloadBoxing {
static void m(long x) { System.out.println("long"); }
static void m(Integer x) { System.out.println("Integer"); }
static void m(int... x) { System.out.println("varargs"); }
static void n(Long x) { System.out.println("Long"); }
public static void main(String[] args) {
m(5); // long (widening wins)
// n(5); // error: int cannot be converted to Long
n(5L); // Long
}
} List.remove(int) vs remove(Object)
List<Integer>has tworemovemethods.remove(1)matchesremove(int index)with no boxing, so it removes by position.- To remove the value 1, pass an object:
list.remove(Integer.valueOf(1)). - This is one of the most common wrapper bugs in interviews and real code.
import java.util.ArrayList;
import java.util.List;
public class RemoveTrap {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(10, 1, 20, 1));
nums.remove(1); // removes index 1 (the value 1 at position 1)
System.out.println(nums); // [10, 20, 1]
nums.remove(Integer.valueOf(10)); // removes the value 10
System.out.println(nums); // [20, 1]
}
} equals across wrapper types
equalsreturns true only when both objects are the same wrapper type with the same value.Integer.valueOf(1).equals(1L)is false, because1Lboxes toLong.- This breaks map lookups: a
Map<Long, String>queried with anintkey boxes toIntegerand finds nothing.
import java.util.HashMap;
import java.util.Map;
public class EqualsTypes {
public static void main(String[] args) {
Long id = 127L;
System.out.println(id.equals(127)); // false: 127 boxes to Integer
System.out.println(id.equals(127L)); // true
System.out.println(id == 127); // true: unboxes id, compares values
Map<Long, String> users = new HashMap<>();
users.put(1L, "Asha");
System.out.println(users.get(1)); // null (Integer key)
System.out.println(users.get(1L)); // Asha
}
} Wrappers are immutable
count++on anIntegerdoes not change the object. It creates (or fetches from the cache) a newIntegerand rebinds the variable.- Passing an
Integerto a method and changing it there never affects the caller. - For a mutable counter use
int,AtomicInteger,LongAdder, ormap.merge(key, 1, Integer::sum).
import java.util.concurrent.atomic.AtomicInteger;
public class ImmutableWrapper {
static void bump(Integer x) { x++; } // changes only the local copy
static void bump(AtomicInteger x) { x.incrementAndGet(); }
public static void main(String[] args) {
Integer a = 5;
bump(a);
System.out.println(a); // 5
AtomicInteger b = new AtomicInteger(5);
bump(b);
System.out.println(b.get()); // 6
}
} Performance: avoid hidden boxing
- Each boxing outside the cache allocates an object. In a hot loop that means millions of short-lived objects and extra garbage collection.
- Classic mistake:
Long sum = 0L;in a loop. Everysum += iunboxes, adds, and boxes a newLong. - Use primitive streams (
IntStream,mapToInt,sum()) instead ofStream<Integer>when doing math. - For huge numeric collections, use arrays or primitive collection libraries instead of
List<Integer>.
import java.util.List;
public class BoxingCost {
public static void main(String[] args) {
long t1 = System.nanoTime();
Long slow = 0L;
for (long i = 0; i < 10_000_000; i++) slow += i; // boxes every iteration
long t2 = System.nanoTime();
long fast = 0L;
for (long i = 0; i < 10_000_000; i++) fast += i; // pure primitive
long t3 = System.nanoTime();
System.out.println("Long: " + (t2 - t1) / 1_000_000 + " ms, long: " + (t3 - t2) / 1_000_000 + " ms");
List<Integer> marks = List.of(70, 85, 90);
int total = marks.stream().mapToInt(Integer::intValue).sum(); // no boxing in sum
System.out.println(total); // 245
}
} Parsing pitfalls and NumberFormatException
parseIntthrowsNumberFormatExceptionfor empty strings, spaces, decimals ("3.5"), or values out of range. Calltrim()on user input first.- A leading
+or-is allowed:parseInt("+7")is 7. parseInt(null)also throwsNumberFormatException, whileDouble.parseDouble(null)throwsNullPointerException.- Java 8 added unsigned helpers:
Integer.parseUnsignedInt,Integer.toUnsignedString,Integer.divideUnsigned.
public class SafeParse {
static int parseOr(String s, int fallback) {
if (s == null) return fallback;
try {
return Integer.parseInt(s.trim());
} catch (NumberFormatException e) {
return fallback;
}
}
public static void main(String[] args) {
System.out.println(parseOr(" 42 ", -1)); // 42
System.out.println(parseOr("4.2", -1)); // -1
System.out.println(parseOr("abc", -1)); // -1
System.out.println(parseOr(null, -1)); // -1
}
} Tricky Interview Points
Q1) What is a wrapper class?
Answer A final, immutable class in java.lang that wraps one primitive value inside an object, such as Integer for int and Character for char.
Q2) Why do we need wrapper classes?
Answer Collections and generics need objects, wrappers can represent null (no value), they provide utility methods and constants, and many APIs accept only Object.
Q3) List all primitive types and their wrapper classes.
Answer byte-Byte, short-Short, int-Integer, long-Long, float-Float, double-Double, char-Character, boolean-Boolean.
Q4) What are autoboxing and unboxing?
Answer Autoboxing is the automatic conversion of a primitive to its wrapper (via valueOf). Unboxing is the reverse (via xxxValue). Both were added in Java 5 and are done by the compiler.
Q5) parseInt vs valueOf?
Answer Integer.parseInt(String) returns a primitive int. Integer.valueOf(String or int) returns an Integer object and uses the -128 to 127 cache.
Q6) Why is Integer 127 == Integer 127 true but 128 == 128 false?
Answer Autoboxing uses Integer.valueOf, which caches -128 to 127. == compares references: the cached values share one object, while 128 creates two separate objects.
Q7) Which wrapper classes have a cache?
Answer Byte (all values), Short, Integer, and Long (-128 to 127), Character (0 to 127), and Boolean (TRUE / FALSE). Float and Double have no cache.
Q8) What happens when you unbox null?
Answer A NullPointerException, because unboxing calls intValue() on a null reference.
Q9) Are wrapper classes mutable?
Answer No. They are immutable and final. Operations like count++ create a new object and rebind the variable.
Q10) What is the parent class of numeric wrappers?
Answer The abstract class java.lang.Number. Character and Boolean extend Object directly.
Q11) Why are wrapper constructors deprecated?
Answer new Integer(5) always allocates and skips the cache. They were deprecated in Java 9 and marked for removal in Java 16; use valueOf or autoboxing instead.
Q12) What does list.remove(1) do on a List<Integer>?
Answer It removes the element at index 1, because remove(int) matches without boxing. Use list.remove(Integer.valueOf(1)) to remove the value 1.
Q13) Given m(long) and m(Integer), which does m(5) call?
Answer m(long). Overload resolution tries widening before boxing, and boxing before varargs.
Q14) Does Long.valueOf(1).equals(1) return true?
Answer No. The argument 1 boxes to Integer, and equals requires the same wrapper type. Use 1L or compare primitive values.
Q15) What is the difference between Boolean.parseBoolean and Boolean.getBoolean?
Answer parseBoolean converts a string ("true" in any case gives true). getBoolean reads a system property with that name and returns true only if the property is set to "true".
Q16) Is autoboxing free?
Answer No. Outside the cache it allocates objects, adds GC pressure, and can hide NullPointerExceptions. Prefer primitives and primitive streams in hot loops.
Q17) int vs Integer: which should a JPA entity id or optional form field use?
Answer Integer (or Long), because it can be null before the record is saved or when the user leaves the field empty. A primitive would silently default to 0.
Simple Programs
All wrapper classes: MIN, MAX, and SIZE
public class WrapperRanges {
public static void main(String[] args) {
System.out.println("Byte : " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE + ", " + Byte.SIZE + " bits");
System.out.println("Short : " + Short.MIN_VALUE + " to " + Short.MAX_VALUE + ", " + Short.SIZE + " bits");
System.out.println("Integer : " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + ", " + Integer.SIZE + " bits");
System.out.println("Long : " + Long.MIN_VALUE + " to " + Long.MAX_VALUE + ", " + Long.SIZE + " bits");
System.out.println("Float : " + Float.MIN_VALUE + " to " + Float.MAX_VALUE + ", " + Float.SIZE + " bits");
System.out.println("Double : " + Double.MIN_VALUE + " to " + Double.MAX_VALUE + ", " + Double.SIZE + " bits");
System.out.println("Character: " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE + ", " + Character.SIZE + " bits");
}
} Boxing and unboxing every primitive
public class BoxAll {
public static void main(String[] args) {
Byte b = 10; byte b2 = b;
Short s = 200; short s2 = s;
Integer i = 3000; int i2 = i;
Long l = 40000L; long l2 = l;
Float f = 5.5f; float f2 = f;
Double d = 6.75; double d2 = d;
Character c = 'J'; char c2 = c;
Boolean ok = true; boolean ok2 = ok;
System.out.println(b2 + " " + s2 + " " + i2 + " " + l2);
System.out.println(f2 + " " + d2 + " " + c2 + " " + ok2);
}
} Number converter: decimal to binary, octal, and hex
import java.util.Scanner;
public class NumberConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int n = sc.nextInt();
System.out.println("Binary : " + Integer.toBinaryString(n));
System.out.println("Octal : " + Integer.toOctalString(n));
System.out.println("Hex : " + Integer.toHexString(n).toUpperCase());
System.out.println("Back : " + Integer.parseInt(Integer.toBinaryString(n), 2));
}
} Character analysis of a string
public class CharStats {
public static void main(String[] args) {
String text = "Java 21 Rocks! Learn @ LCG";
int upper = 0, lower = 0, digits = 0, spaces = 0, others = 0;
for (char ch : text.toCharArray()) {
if (Character.isUpperCase(ch)) upper++;
else if (Character.isLowerCase(ch)) lower++;
else if (Character.isDigit(ch)) digits++;
else if (Character.isWhitespace(ch)) spaces++;
else others++;
}
System.out.println("Upper=" + upper + " Lower=" + lower + " Digits=" + digits
+ " Spaces=" + spaces + " Others=" + others);
}
} Sum numbers from text input safely
public class SumFromText {
public static void main(String[] args) {
String csv = "10, 20, abc, 30, , 4.5, -5";
int sum = 0;
for (String part : csv.split(",")) {
String t = part.trim();
try {
sum += Integer.parseInt(t);
} catch (NumberFormatException e) {
System.out.println("Skipping invalid value: \"" + t + "\"");
}
}
System.out.println("Sum = " + sum); // 55
}
} Sum a List<Integer> that contains null
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class NullSafeSum {
public static void main(String[] args) {
List<Integer> marks = Arrays.asList(80, null, 95, 70, null);
// int bad = 0; for (int m : marks) bad += m; // NullPointerException
int total = 0;
for (Integer m : marks) {
if (m != null) total += m;
}
int streamTotal = marks.stream().filter(Objects::nonNull).mapToInt(Integer::intValue).sum();
System.out.println(total + " " + streamTotal); // 245 245
}
} Word frequency with Map<String, Integer>
import java.util.Map;
import java.util.TreeMap;
public class WordFreq {
public static void main(String[] args) {
String text = "java is fun and java is powerful";
Map<String, Integer> freq = new TreeMap<>();
for (String w : text.split("\\s+")) {
freq.merge(w, 1, Integer::sum); // boxing handled by merge
}
System.out.println(freq); // {and=1, fun=1, is=2, java=2, powerful=1}
}
} Wrapper traps in one program
import java.util.ArrayList;
import java.util.List;
public class WrapperTraps {
public static void main(String[] args) {
Integer a = 1000, b = 1000;
System.out.println(a == b); // false: compares references
System.out.println(a.equals(b)); // true
List<Integer> list = new ArrayList<>(List.of(5, 3, 1));
list.remove(1); // removes index 1 (value 3)
System.out.println(list); // [5, 1]
Long big = 10L;
System.out.println(big.equals(10)); // false: Integer vs Long
System.out.println(Boolean.parseBoolean("TRUE")); // true
System.out.println(Boolean.getBoolean("TRUE")); // false: reads system property
System.out.println(Double.MIN_VALUE > 0); // true: smallest positive value
}
} Problem Solving Tricks
- Never compare wrappers with
==. Useequals,Integer.compare, or unbox after a null check. - Remember the two odd names:
intisIntegerandcharisCharacter. - Use
parseXxxwhen you want a primitive andvalueOfwhen you want an object. - Cache ranges to remember: -128 to 127 for Byte, Short, Integer, Long; 0 to 127 for Character; none for Float and Double.
- Before unboxing a value from a
Map, database, or JSON, ask "can this be null?" and usegetOrDefaultif so. - On
List<Integer>,remove(1)removes an index;remove(Integer.valueOf(1))removes a value. - Use
mapToInt(Integer::intValue).sum()instead ofreduce(0, Integer::sum)to avoid boxing. - Never write
Long sum = 0Las a loop accumulator; uselong. Characterhas noparseChar; uses.charAt(0)after checking the length.Double.MIN_VALUEis the smallest positive double. For the most negative use-Double.MAX_VALUE.Boolean.getBooleanreads a system property. To convert text useBoolean.parseBoolean.
Practice Programs List
- Print MIN_VALUE, MAX_VALUE, and SIZE for all eight wrapper classes.
- Box and unbox each primitive type once and print the results.
- Loop i from 120 to 135 and print whether
Integer.valueOf(i) == Integer.valueOf(i); explain where it changes. - Read a number as a String, convert it to int, and print it in binary, octal, and hexadecimal.
- Convert the binary string "110101" and the hex string "1F" to decimal.
- Parse "3.14" to double and handle
NumberFormatExceptionfor "pi". - Write
int safeUnbox(Integer x, int fallback)and test it with null. - Count uppercase, lowercase, digits, spaces, and special characters in a sentence using
Charactermethods. - Find the sum of digits in a String such as "a1b2c3" using
Character.getNumericValue. - Sum an
ArrayList<Integer>that contains null values without throwing an exception. - Show the
List.remove(int)vsremove(Object)difference with a list of integers. - Write overloaded methods
m(long),m(Integer), andm(int...)and predict which onem(10)calls. - Time a loop that sums into
Longvslongfor 10 million iterations and compare. - Write a method
double total(List<? extends Number> nums)and call it with lists of Integer and Double.