I have
System.out.println(2+" "+3);
System.out.println(2+' '+3);
The first one prints 2 3 while the second prints 37 Can any of guys explain why it is printing 37???
Quoting Java Language Specification for Additive Operators:
If the type of either operand of a
+operator isString, then the operation is string concatenation.Otherwise, the type of each of the operands of the
+operator must be a type that is convertible (§5.1.8) to a primitive numeric type
For Numeric Types:
Binary numeric promotion is performed on the operands (§5.6.2)
Binary Numeric Promotion:
[...] Otherwise, both operands are converted to type
int.
So, 2+" "+3 is 2 + " ", which is a string concatenation, and String + 3 is also a string concatenation, hence 2 + " " + 3 is "2" + " " + "3" which means "2 3".
2+' '+3 is 2 + ' ', and the space literal is a char, so it is converted to int (32), and 2 + 32 + 3 is 37.
If the literals had been variables, it would actually be like this, where the assignment to a variable is only used to illustrate the type of the intermediate result:
// String concatenation
String s = new StringBuilder().append(2).append(" ").append(3).toString();
System.out.println(s);
// Numeric addition
int n = 2 + (int)' ' + 3;
System.out.println(n);
Both append() and println() are overloaded, so they are not all the same method.
Since they are literals, and not variables, the compiler will do it at compile-time, and you really get this (try disassembling a .class file to see for yourself):
System.out.println("2 3");
System.out.println(37);
' '= 32 in ascii .
a:) System.out.println(2+" "+3); // string concatenation
b:) System.out.println(2+' '+3); // 2+ 32(32 ascii valur for space)+3 so 37
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