This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
On Marcus green exam1 Question 25 ask the following question:
What will happen if you attempt to compile and run the following code?
Integer ten=new Integer(10); Long nine=new Long (9); System.out.println(ten + nine); int i=1; System.out.println(i + ten);
1) 19 followed by 20 2) 19 followed by 11 3) Compile time error 4) 10 followed by 1
the answer given is 3.
This answer didn't seem correct to me so I typed in the program and complied it. The program ran and printed 19 followed by 11 answer 2. I'm I missing somthing about this question? Even if the wrapper class didn't know how to convert the objects and add them would it not use the toString() method and and print the string for both object since it is in a print statement?
would it not use the toString() method and and print the string for both object since it is in a print statement?
If it did that you would get "109" and "110" printed. The + would have to be taken as the concatenation operator.
In the case of ten + nine neither of the operands is a string, so the + is taken as the arithmetical add operator. Add needs primitives to operate upon. In 1.4 the wrapper classes canot be converted to primitives so you get a compilation error. As previously mentioned, in 5.0 an unboxing conversion takes place for the wrapper operands and the add operation succeeds.
Moral: if you are studying for SCJP 1.4, then use the 1.4 mocks and use the 1.4.2_<latest> compiler. If you are studying for SCJP 5.0, then be awake for these sometimes suprising changes.