Comparing boxed Long values 127 and 128

TL;DR Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects. Long (pun intended) version Why there is problem in comparing Long variable with … Read more

What code does the compiler generate for autoboxing?

You can use the javap tool to see for yourself. Compile the following code: public class AutoboxingTest { public static void main(String []args) { Integer a = 3; int b = a; } } To compile and disassemble: javac AutoboxingTest.java javap -c AutoboxingTest The output is: Compiled from “AutoboxingTest.java” public class AutoboxingTest extends java.lang.Object{ public … Read more

Why aren’t Integers cached in Java?

It should be very clear that caching has an unacceptable performance hit — an extra if statement and memory lookup every time you create an Integer. That alone overshadows any other reason and the rest of the agonizing on this thread. As far as responding “correctly” to ==, the OP is mistaken in his assumption … Read more

Why does autoboxing make some calls ambiguous in Java?

When you cast the first argument to Object yourself, the compiler will match the method without using autoboxing (JLS3 15.12.2): The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the … Read more

Is autoboxing possible for the classes I create?

In short, no. There’s no way to get that to compile. Java only defines a limited set of pre-defined boxing conversions. From the JLS, section 5.1.7: Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions: From type boolean to type Boolean … Read more

Why does int num = Integer.getInteger(“123”) throw NullPointerException?

The Big Picture There are two issues at play here: Integer getInteger(String) doesn’t do what you think it does It returns null in this case the assignment from Integer to int causes auto-unboxing Since the Integer is null, NullPointerException is thrown To parse (String) “123” to (int) 123, you can use e.g. int Integer.parseInt(String). References … Read more