Challenge - 5 Problems
Unboxing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this unboxing example?
Consider the following Java code. What will be printed when it runs?
Java
Integer a = 1000; int b = a; System.out.println(b == a);
Attempts:
2 left
💡 Hint
Remember that unboxing converts Integer to int automatically.
✗ Incorrect
The Integer 'a' is unboxed to int 'b'. The comparison 'b == a' compares int and Integer, but 'a' is unboxed too, so it compares two ints with the same value, resulting in true.
❓ Predict Output
intermediateWhat is the output when comparing Integer objects with ==?
What will this Java code print?
Java
Integer x = 127; Integer y = 127; System.out.println(x == y); Integer m = 128; Integer n = 128; System.out.println(m == n);
Attempts:
2 left
💡 Hint
Integer caching affects values between -128 and 127.
✗ Incorrect
Java caches Integer objects for values from -128 to 127. So x and y point to the same object, making x == y true. For 128, m and n are different objects, so m == n is false.
🔧 Debug
advancedIdentify the runtime error caused by unboxing
What error will this code produce when run?
Java
Integer a = null; int b = a; System.out.println(b);
Attempts:
2 left
💡 Hint
Unboxing null causes a problem at runtime.
✗ Incorrect
Unboxing tries to convert null Integer to int, which causes a NullPointerException at runtime.
❓ Predict Output
advancedWhat is the output of this mixed boxing and unboxing code?
Analyze the output of this Java code snippet:
Java
Integer i = 10; int j = 10; System.out.println(i.equals(j)); System.out.println(i == j);
Attempts:
2 left
💡 Hint
Remember how equals and == behave with Integer and int.
✗ Incorrect
i.equals(j) returns true because equals compares values after unboxing j. i == j compares Integer and int, unboxing i, so true.
🧠 Conceptual
expertHow many Integer objects are created in this code?
Consider this Java code snippet. How many distinct Integer objects are created during execution?
Java
Integer a = 100; Integer b = 100; Integer c = new Integer(100); Integer d = Integer.valueOf(100); Integer e = 200; Integer f = 200;
Attempts:
2 left
💡 Hint
Remember Integer caching and when new objects are created.
✗ Incorrect
a and b use cached Integer for 100 (one object), c creates a new object, d uses cached object again, e and f for 200 create two new objects (no cache). Total 4 objects: one cached for 100, one new from c, two new for 200.
