Wrapper Classes in Java. Practical Tasks
The line int count = stock.get("banana"); has no explicit intValue() call, yet it throws a NullPointerException when the key "banana" is missing from a Map<String, Integer>. Bugs like this are easier to spot after a few exercises than after rereading the rules.
This page collects Java wrapper classes exercises (Integer, Long, Double, Boolean) and autoboxing practice: the valueOf(), parseXxx() and xxxValue() methods, the Integer cache and comparison with == and equals(), unboxing null, autoboxing in loops, and overload resolution with boxing and varargs. Read the module lessons first: Wrapper Classes in Java, Autoboxing and Unboxing in Java and Method Overloading with Widening, Autoboxing and Varargs.
Double Methods: valueOf(), parseDouble() and xxxValue()
Write a program that works with the Double class and prints the result of each step to the console.
- Create
Doubleobjects using both forms ofvalueOf(): from adoubleprimitive and from a string. - Convert the string
"300.99"to adoubleprimitive withDouble.parseDouble(). - Convert a
Doubleobject with the value 300.99 to every numeric primitive type usingbyteValue(),shortValue(),intValue(),longValue(),floatValue()anddoubleValue(). Explain whybyteValue()does not return 300. - Convert a literal of type
doubleto a string:String d = Double.toString(3.14); - Try to parse the strings
"3,14"and" 3.14 "withDouble.parseDouble(). Catch the parsing error and print a message like "Not a number: ..." instead of letting the program crash.
Nuance
Double.parseDouble() accepts only a dot as the decimal separator, regardless of locale, so "3,14" causes a NumberFormatException. Unlike Integer.parseInt(), it trims whitespace around the string on its own: " 3.14 " is parsed as 3.14.
Wrapper Class Methods Table
Fill in the table: put an "x" where the row's method exists in the column's wrapper class. In the last column, mark whether the method is static or an instance method.
| Method | Boolean | Byte | Character | Double | Float | Integer | Long | Short | Static? |
|---|---|---|---|---|---|---|---|---|---|
| byteValue() | |||||||||
| doubleValue() | |||||||||
| floatValue() | |||||||||
| intValue() | |||||||||
| longValue() | |||||||||
| shortValue() | |||||||||
| parseXxx(String) | |||||||||
| parseXxx(String, int radix) | |||||||||
| valueOf(String, int radix) | |||||||||
| toString() | |||||||||
| toString(primitive) | |||||||||
| toString(primitive, int radix) |
How to check yourself
The javap java.lang.Byte command prints all method signatures of a class (do the same for each wrapper); your IDE's autocomplete after Byte. shows the same. Remember that Character and Boolean do not extend Number, so they do not have its xxxValue() methods.
Comparing Integer and Long: == or equals()
Write a program that compares wrapper objects in different ways. Before running it, write down the expected result of each line, then compare it with the actual output.
- Declare
Integer a = 127, b = 127;andInteger c = 128, d = 128;. Print the results ofa == b,c == d,c.equals(d)andc <= d && c >= d. - Declare
Long f = 128L;and printf == 128,f.equals(128)andf.equals(128L). - Write a static method
boolean sameValue(Integer x, Integer y)that compares the values and throws no exception when one or both arguments arenull(twonullvalues are considered equal). Test it on the pairs (1000, 1000), (null, 5) and (null, null). - Run the program with the JVM option
-XX:AutoBoxCacheMax=1000. Which output line changed, and why did the others stay the same?
Hint
Two wrappers compared with == are compared by reference, and valueOf(), which autoboxing calls, returns the same object only for values in the cache. For sameValue(), Objects.equals() will help.
Long or long: Autoboxing in a Loop
See in practice what autoboxing costs in a “hot” loop.
- Write a method
static Long sumBoxed(int n)that sums the numbers from 0 to n - 1 into a variable of typeLong, and a methodstatic long sumPrimitive(int n)with an accumulator of typelong. - Call both methods with
n = 10_000_000and time each call withSystem.nanoTime(). Print the sum and the time in milliseconds. Both versions must print the sum49999995000000. - Repeat the measurement 5 times in a loop and compare the time of the first and the last repetition.
- Count how many new
Longobjects a call tosumBoxed(10_000_000)creates, given thatLong.valueOf()caches values from -128 to 127. Write the answer as a comment in the code.
About the timings
The timings depend on your computer and JVM version, so what matters is the difference of several times, not exact milliseconds. The first repetitions are slower because of JIT warm-up; for accurate measurements use the JMH library. To count the objects, find the first iteration where the sum exceeds 127.
Which Overloaded Method Is Called: Widening, Boxing, Varargs
Given a class with four overloaded print() methods:
public class OverloadQuiz {
static void print(long x) { System.out.print("long "); }
static void print(Integer x) { System.out.print("Integer "); }
static void print(Object x) { System.out.print("Object "); }
static void print(int... x) { System.out.print("int... "); }
public static void main(String[] args) {
byte b = 1;
char ch = 'a';
Integer boxed = 3;
Character c = 'a';
print(b);
print(5);
print(boxed);
print(ch);
print(c);
print(3.0);
print(1, 2);
print();
// print(null);
}
} - Without running the program, write down what each call prints and which resolution phase (1, 2 or 3) selects the method. Then run the program and check your answers.
- Add the method
static void print(double x). Predict which words in the output change, and verify. - Uncomment the
print(null)call. Will the program compile? Explain the compiler message.
Resolution order
For each call go through the phases in order: 1 — exact match and widening (primitives and references), 2 — boxing and unboxing, 3 — varargs expansion. As soon as a phase finds at least one applicable method, later phases are not considered. In phases 1 and 2 the method print(int... x) is seen as a method with an int[] parameter.
What Each Exercise Practices
The first two exercises test the wrapper class methods, the next three cover autoboxing and unboxing, and the last one covers overload resolution. If an exercise does not work out, go back to the lesson section in the table: it has the rule and an example with output.
| Exercise | What it checks | What to review |
|---|---|---|
| Double methods | valueOf() vs parseDouble(), xxxValue(), NumberFormatException | Wrapper Class Methods |
| Wrapper methods table | which methods each wrapper has, static vs instance | The Number Class |
| Comparing Integer and Long | cache -128..127, == vs equals(), comparison with null | Comparing Wrappers: == or equals() |
| NullPointerException on unboxing | Map.get(), ternary operator, Boolean in if | NullPointerException When Unboxing null |
| Long or long in a loop | the cost of autoboxing, LongStream | Java Autoboxing Performance: Boxing in Loops |
| Which method is called | overload resolution phases, remove(int) vs remove(Object) | The Three Phases of Overload Resolution |
Common Mistakes in Solutions
Most mistakes in these exercises come not from unfamiliar syntax but from testing on “convenient” data: small numbers, filled-in keys, a single run. Before you call a solution done, check it on boundary values.
- Comparing two Integer objects with ==. The test passes for values from -128 to 127 and fails on real data.
- try-catch instead of a fix. Catching
NullPointerExceptionhides the bug; it is better to substitute a default before unboxing (getOrDefault(),Boolean.TRUE.equals()). - A single timing measurement. The first run of a loop includes JIT compilation, so compare results after several repetitions.
- Choosing a method by “the closest type”. The compiler stops at the first phase where a suitable method is found, even if a later phase has a method with a closer type.
Check your code
Before you call an exercise done, review your code against a few basic style rules: meaningful variable names, no deprecated new Integer(...) constructors, and primitives wherever a value can never be absent.
Frequently Asked Questions
In what order should I solve the wrapper class exercises?
Start with the Double methods and the methods table: they check the basic API. The exercises on Integer comparison, unboxing null and autoboxing in a loop are independent, so you can do them in any order. Leave the overloaded methods exercise for last: it cannot be solved without understanding autoboxing.
Can I create wrappers with new Integer() or new Double() in my solutions?
Better not to: these constructors were deprecated in Java 9 and marked forRemoval in Java 16, so the compiler warns about them. Use valueOf(), parseXxx() or autoboxing instead. More in the section valueOf() Instead of Constructors.
How do I check my solution if there is no reference answer?
The autoboxing and overloading exercises include the expected output or tell you to run the code. Write down your prediction first, then run the program and explain every difference using the rules from the lesson. If you cannot explain a line of output, go back to the lesson section from the table above.
What wrapper class questions come up most often in Java interviews?
Why Integer 127 == 127 gives true while 128 == 128 gives false; where NullPointerException appears on unboxing; why Long.valueOf(5).equals(5) returns false; and what list.remove(1) removes from a List<Integer>. All four are covered by the exercises on comparing Integer, unboxing null and overloading.
Comments