Given the following code:
...
Integer i = new Integer( 1 );
System.out.println( ++i );
...
What is the output?
The output is:
2This is surprising: How is it possible use ++ operator to objects? The answer is the autoboxing, what is available java 5 and above.
What's happening in the
System.out.println( ++i );
line?
Java unboxes, increments, reboxes the variable i, this is a good sample to autoboxing.
Puzzle 2
Given the following code:
class Boxing {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
}
}
What is the output?
The output is NullPointerException.
Why?
Variable x refers to null so the doStuff() method called with null parameter and at the z2 + z expression NullPointerException is trowed.
No comments:
Post a Comment