Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation Order with string and ints

  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?

like image 615
Akash Arjun Avatar asked Dec 03 '25 18:12

Akash Arjun


2 Answers

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.

like image 127
YCF_L Avatar answered Dec 06 '25 09:12

YCF_L


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

like image 25
Wassim Al Ahmad Avatar answered Dec 06 '25 07:12

Wassim Al Ahmad