Page 1 of 1

About Question enthuware.ocpjp.v21.2.3343 :

Posted: Wed Jan 08, 2025 10:16 am
by n199a_
Identify examples of autoboxing.
[+] Integer i = 10;
[+] Integer getValue(){ return 2; }
[-] Long getValue(){ return 2; } - An int cannot be autoboxed into a Long. return 2L; would have been valid.
[+] System.out.println(2+"");

For some reason, the correct option is

Code: Select all

System.out.println(2+"");
However, we have excellent Java documentation (https://docs.oracle.com/javase/tutorial ... oxing.html), which says it all, quote:
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
Therefore, your item "System.out.println(2+"");" should be marked as INCORRECT.

Re: About Question enthuware.ocpjp.v21.2.3343 :

Posted: Wed Jan 08, 2025 10:39 am
by admin
Did you read the explanation? The expression 2+"" will cause primitive value 2 to be autoboxed into Integer object containing 2 first.

As per JLS 21 section 15.18:
If the type of either operand of a + operator is String, then the operation is string concatenation.
...
If only one operand expression is of type String, then string conversion (ยง5.1.11) is performed on the other operand to produce a string at run time.
and section 5.1.11 (String conversion):
If T is byte, short, or int, then use new Integer(x).
So it is quite clear that autoboxing will be used while evaluating 2+"".