Booleans, conditional operators and autoboxing

The difference is that the explicit type of the returnsNull() method affects the static typing of the expressions at compile time: E1: `true ? returnsNull() : false` – boolean (auto-unboxing 2nd operand to boolean) E2: `true ? null : false` – Boolean (autoboxing of 3rd operand to Boolean) See Java Language Specification, section 15.25 Conditional … Read more

How does auto boxing/unboxing work in Java?

When in doubt, check the bytecode: Integer n = 42; becomes: 0: bipush 42 2: invokestatic #16 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 5: astore_1 So in actuality, valueOf() is used as opposed to the constructor (and the same goes for the other wrapper classes). This is beneficial since it allows for caching, and doesn’t force the creation … Read more

Why do we use autoboxing and unboxing in Java?

Some context is required to fully understand the main reason behind this. Primitives versus classes Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double). On the other hand, class … Read more

How to convert int[] into List in Java?

Streams In Java 8+ you can make a stream of your int array. Call either Arrays.stream or IntStream.of. Call IntStream#boxed to use boxing conversion from int primitive to Integer objects. Collect into a list using Stream.collect( Collectors.toList() ). Or more simply in Java 16+, call Stream#toList(). Example: int[] ints = {1,2,3}; List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList()); … Read more

Weird Integer boxing in Java

The true line is actually guaranteed by the language specification. From section 5.1.7: If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions … Read more