In Java 3 = 12
virtualspecies.com
virtualspecies.com
Uh, no, I suspect this is an example of "magical thinking" by the author.
Far more logical theory: It's working left-to-right, doing int-to-int addition until it hits the first string, which is "=", at which point it is locked into doing string-to-string concatenation for the remainder.
String concatenation is one of the few places Java has overloaded operators, and this quirk (and reader confusion!) is an fair example of why Java does NOT allow users to overload operators for their own classes.
No, because int + int -> int, int + string -> string, and string + int -> string.
System.out is irrelevant, except that it's what causes the result of the computation to be printed.
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result.
Overloading + is a huge design mistake in many languages and a source of bugs.
$ perl -E'say 1 + 2 . "=" . 1 . 2'
3=12
$ perl -E'say 1 + 2 . "=" . (1 + 2)'
3=3
$ perl6 -e'say 1 + 2 ~ "=" ~ 1 ~ 2'
3=12
$ perl6 -e'say 1 + 2 ~ "=" ~ 1 + 2'
3=3System.out.println((1 + 2) + " = " + (1 + 2));
TypeError: unsupported operand type(s) for +: 'int' and 'str' TypeError: String can't be coerced into Fixnumscala> 1+2+"="+1+2 res1: String = 3=12
1+2 = 3
Then hits string
Optimiser changes + to String builder
So you get
StringBuilder sb = new StringBuilder();
sb.append(3);
sb.append("=");
sb.append(1);
sb.append(2);