String s1 = "six" + 3 + 3;
String s2 = 3 + 3 + "six:";
System.out.println(s1);
System.out.print(s2);
Output :
six33
6six:
Why is 3+3 not added in the first one but is added in the second one?
The order of the operation is important
In the first one the concatenation works like so :
String s1 = "six" + 3 + 3;
"six3" + 3 // string plus int return string
"six33" // string plus int return string
In the second one :
String s2 = 3 + 3 + "six:";
6 + "six" // int plus int return int
"6six" // int plus string return string
For more details read documentation of Operators and 15.7. Evaluation Order
All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
In S1, the compiler reads (six) characters, then reads and reads. The numerical value of number 3 cannot be summed with text (six), as a character and added after x, then reads 3 and added after the first 3.
In s2 he reads 3 and then 3 can execute the process collected by the compiler and prints 6 directly and then reads (six) can not be collected will be printed after the number 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With