What is the output for the following lines of code? 1: System.out.println(" " +2 + 3); 2: System.out.println(2 + 3); 3: System.out.println(2 + 3 +""); 4: System.out.println(2 + "" +3); A) Compilation error at line 3 B) Prints 23, 5, 5 and 23. C) Prints 5, 5, 5 and 23. D) Prints 23, 5, 23 and 23. B is correct answer, however I don't understand why the third line prints 5 instead of 23. What's the difference between line 1 and line 3? Thanks Michael
rafa
Greenhorn
Joined: Feb 13, 2002
Posts: 6
posted
0
are u sure that answer is b. According to me it is c.
Raja Islam
Ranch Hand
Joined: Dec 07, 2001
Posts: 74
posted
0
The answer B is a valid answer.
Mathew Sam
Ranch Hand
Joined: Dec 19, 2001
Posts: 124
posted
0
+ operator is overloaded. If one of the operand is of type String it performs concatenation. 1: System.out.println(" " +2 + 3); If you take line number 1, associativity is from left to right so first it does " "+2 and the output will be string.that stirng again conatenated with 3.So output will be 23. 3: System.out.println(2 + 3 +""); If you take line number 3,it does 2+3 =5 ,then 5+"" =5
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
posted
0
Not an errata and could be useful to other people. Moving this to the study forum... [ February 28, 2002: Message edited by: Valentin Crettaz ]