I haven't understood the reason why integer is treated as string literal in concatenation. E.g.
String s=10+30+" Sachin "+40+40;
System.out.println(s);
The output is: 40 Sachin 4040
.
Why 40+40
is not getting added and why 10+30
is getting added?
The expression is evaluated left to right. The first two operands are both int
(10 and 30), so the first +
performs addition.
The next +
gets an int
operand (40) and a String
operand (" Sachin "), so it converts the int
to String
and performs String
concatenation.
The next +
operators get a String
operand and an int
operand, and also perform String
concatenation.
If you want a different evaluation order, use parentheses :
String s=10+30+" Sachin "+(40+40);
This will output 40 Sachin 80
.
This is because Java evaluates operands from left to right. Quoting section 15.7:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
String s=10+30+" Sachin "+40+40;
// ^^^^^ + the operands are of type int so int addition is performed
String s=40+" Sachin "+40+40;
// ^^^^^^^^^^^^^ + the operands are of type int and String so String concatenation is performed
String s="40 Sachin "+40+40;
// ^^^^^^^^^^^^^^^ + the operands are of type int and String so String concatenation is performed
String s="40 Sachin 40"+40;
// ^^^^^^^^^^^^^^^^^ + the operands are of type int and String so String concatenation is performed
String s="40 Sachin 4040";
The behaviour of +
when one of the operands is a String
is specified in section 15.18.1 about the "String Concatenation Operator +
":
If only one operand expression is of type
String
, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
Because that's how it is implemented, because + is both used for adding numbers, as for String concatenation.
The first time, neither of the parts is a String, but both are numerical values that can be added, so it's used to add the values.
But, as soon as one part of the two is a String, it is used for String concatenation.
Change your code like this:
String s=10+30+" Sachin "+(40+40);
Addition is left associative. let's see it step by step
10+30+" Sachin "+40+40
----- -------
40 +" Sachin "+40+40 <--- here both operands are integers with the + operator, which is addition
---
"40 Sachin "+40+40 <--- + operator on integer and string results in concatenation
-----------
"40 Sachin 40"+40 <--- + operator on integer and string results in concatenation
--------------
"40 Sachin 4040" <--- + operator on integer and string results in concatenation
-----------------
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