Why is the output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the output?

System.out.println(1 + 2 + "3" + 4 + 5); Output: 3345 Why is it not 339?

18th Jan 2019, 3:41 AM
Sami
5 Answers
+ 5
This is how I see it, hope I get it right; 1 + 2 is done as arithmetic addition operation When it gets to "3", the + operator is understood as concatenation operator, because "3" is a string, the result of (1 + 2) is then casted as string, concatenated with "3". The 4 and 5 are also treated as string because they came following the "3", hence they are concatenated instead of being added. Hth, cmiiw
18th Jan 2019, 4:03 AM
Ipang
+ 4
hi Samira that is because 3 is a string and all the other numbers are integer values. i hope this helps
18th Jan 2019, 3:48 AM
Ollie Q
Ollie Q - avatar
+ 4
You asked why not 339, so you are aware of the auto type casting and plus operator method overloading. The reason that 4+5 is not arithmetic is because of operator precedence, while ** > * > + int + and float + and String + has the same precedence. Hence, if we add parathesis to indicate the sequence, it's like this: ((((1+2)+"3")+4)+5) Thus the fourth plus sign is string concantention of "334"+"5" instead of 4+5
18th Jan 2019, 5:03 AM
Gordon
Gordon - avatar
+ 3
Thank you so much for these answers! 😊
18th Jan 2019, 7:05 AM
Sami
+ 1
Because 3 is a string, that is why you do not add 4 + 5? Then why is 1 + 2 added together?
18th Jan 2019, 3:50 AM
Sami