Now, when we covered previous example this question should be easy for you.
Q: What value will be assigned to variable b in the code below?
public class Test{
public static void main(String[] args){
Boolean a = null;
boolean b = a;
}
}
A:no value will be assigned to b due to exception during execution.
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:4)
Code in the question is equal to this one
public class Test{
public static void main(String[] args){
Boolean a = null;
boolean b = a.booleanValue(); //null.booleanValue()
}
}
Q: What value will be assigned to variable c in the example below?
public class Test{
public static void main(String[] args){
Long a = 20L;
long b = 20;
boolean c = a.equals(b);
}
}
A:the correct answer – true.
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc2_w #7 // long 20l
3: invokestatic #9 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
6: astore_1
7: ldc2_w #7 // long 20l
10: lstore_2
11: aload_1
12: lload_2
13: invokestatic #9 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
16: invokevirtual #15 // Method java/lang/Long.equals:(Ljava/lang/Object;)Z
19: istore 4
21: return
}
which is the same as
public class Test{
public static void main(String[] args){
Long a = 20L;
long b = 20;
boolean c = a.equals(Long.valueOf(b));
}
}
Q: What value will be assigned to variable c in the example below?
public class Test{
public static void main(String[] args){
Long a = 20L;
boolean c = a.equals(20);
}
}
A:the correct answer – false.
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc2_w #7 // long 20l
3: invokestatic #9 // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
6: astore_1
7: aload_1
8: bipush 20
10: invokestatic #15 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
13: invokevirtual #20 // Method java/lang/Long.equals:(Ljava/lang/Object;)Z
16: istore_2
17: return
}
In this example there is no type reference so 20 is represented as most appropriate integer type.
public class Test{
public static void main(String[] args){
Long a = 20L;
boolean c = a.equals(Integer.valueOf(20));
}
}
So, even if autoboxing/unboxing logic seems pretty straightforward and easy you still need to keep attention to details. As best practice to avoid memory and/or performance-related issues you shouldn’t rely on the autoboxing/unboxing mechanism in your code. The most appropriate case when this mechanism is really needed is when you store primitive types in the collection.