+ 2

Why are the numbers treated differently

System.out.println(1+2+3+"hello"+4+5); Outputs:6hello45 The numbers (1,2,3) are treated as integers while (4,5) treated as strings

13th May 2017, 9:30 PM
tylerasa
tylerasa - avatar
3 Antworten
+ 7
It's because it reads it from left to right, so in steps: 1+2=3 3+3=6 6+hello=6hello 6hello+4=6hello4 (just adding a number to a string) 6hello4+5=6hello45 (adding a numer to a string again) If you'd do: 1+2+3+"hello"+(4+5) it would calculate 4+5 instead of adding them to the string
13th May 2017, 9:38 PM
Maart
Maart - avatar
+ 1
compiler does have some priorities in performing mathematical calculations on different data types. it solves mathematical expression from left to right, on left most it found an int adding into another 1 + 2 = 3 then another int 3+3 = 6 then it found a string and merged it 6 + hello = 6hello now 6hello is a complete string, then it will add 4 in it 6hello + 4 = 6hello4 and then it find int 5 to add in a string 6hello4+5 = 6hello45
13th May 2017, 9:59 PM
Hamza Ahmed Khan
Hamza Ahmed Khan - avatar