More AutoBoxing in Java

Previously when we touched on AutoBoxing in Java, we only had a glimpse of what Java 5 onwards could do. If you are studying for SCJP 6 (the latest SCJP as of date of print), this will definitely help yourself to be prepared for the Exam. Now let’s have a look at some of the examples.

Autoboxing SCJP Java 6 tips

It is definitely correct if one does a comparison of numeric values like the following example.

Integer first = 1;
int one = 1;

if (one == first)
  System.out.println("Same value");

Now what about if I were to do it this way?

Integer First = 1;
int one = first;

System.out.println("Value of one is: " + one);

So now we know that Integer and int can co-relate with each another ever since AutoBoxing was introduced into Java 5. Now here’s a question. Which of these is illegal?

Integer a = 01;
Integer string = null;
Integer lock = 2.4;
Integer enum = 1;

The answer to this is a little bit tricky.

First there are only 2 right answers. The answers for this little quiz is Number 1 and 2 is legal. Yes, and this will be the outcome if they were both printed seperately.

Integer a is 1
Integer string is null

Number 3 and 4 are both deemed illegal and would not even be able to compile due to the value 2.4 is a double that cannot be casted to Integer. For Number 4, enum is a reserved word. Some of us might even get confused as to why number 2 is right? Shouldn’t string be a reserved word?

Of course, String is a reserved word, while string is not a reserved word. One is uppercase, one is lowercase. Java is indeed more flexible compared to the Java 1.4 days.


  1. danielctw March 3, 2011

Leave a Reply to danielctw Cancel reply