[Logo]
Forums Register Login
The + operator is confusing, help!
What is the output for the following lines of code? /please explain in terms of precedence of string concatenation vs, addition. ans is 5.
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.
Hi
Here is the explanation
a)
First " "+2+3 .See it is evaulation not assignment of operator. Here eveulation order is left to right. So first 2 will be converted to string( due to " ") and then 3 is converted to string.
As both of them are string they are concatenated. Ans 23
b) 2+3
herr simple addition of variable is made and displayed as 5
c)
Is same as previous one. Only difference is that 5 is later converted to string.
d) 2+" "+3
Here 2 is converted to string and later 3 is converted into string and both are concatednated. SO answer is 23
so i think answer should be B not D.
If i am wrong then correct me.
parag

Answer is b.
Whenever a string in involved anywhere in the expression, the '+' operator is in string-context. So 2+3+"" is exactly the same as ""+2+3 and as 2+""+3 and all result in 23. So D is the correct answer
Chris is right, folks. The correct answer is D. Whenever you have a string in an expression, the other values are promoted to strings. since "" is a string (the empty string, not the null string), 2 and 3 are promoted to "2" and "3" respectively and the + operator here functions as the concatenation operator and concatenates all the three strings.
HTH
Shashi
Parag and Rob are right. Run this prog and see for yourself
//TestStringprint.java
public class TestStringprint
{
public static void main(String[] args)
{
System.out.println(""+2 + 3);
System.out.println(2 + 3);
System.out.println(2 + 3 +"");
System.out.println(2 + "" +3);
}
}
Hi Folks,
If you look at D and B the only difference is the 3rd one so lets look at that:
2+3+""
just like pure mathematics, this line reads from left to right (since addition and concatenation have the same level of importance in order of operations here). First we evaluate only the first '+' which is 2+3...meaning 5, leaving just 5+"" which then converts it to "5" rather than "23".
Meaning the correct answer is B.
The presence of a String in an equation does not influence the outcome so much as the location of that String in the equation.
I hope that helps a bit and also that it did not come across as condescending. Have a good one.
-Paul

[This message has been edited by Paul Caudle (edited November 07, 2000).]
Chrisis, may I ask you to register with proper name?
You can read this post for more details. We are glad to see you here, just a little formality´┐Ż
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Nov 23, 2017 15:50:01.