Consider the below code snippet -
public class Student {
public static void main(String args[]) {
int a = 3;
int b = 4;
System.out.println(a + b +" ");
System.out.println(a + b +" "+ a+b);
System.out.println(""+ a+b);
}
}
The output for the above snippet is coming as -
7
7 34
34
It is clear from the output that if we use String at first in the print statement then the integers are concatenated. But, if we use integer at first then the values are added and displayed.
Can someone please explain why is this behavior?
I even tried to look at the implementation of println() method in PrintStream class but could not figure out.
Actually it's not println()
implementation who's causing that, this is Java
way to treat the +
operator when dealing with Strings
.
In fact the operation is treated from left to right so:
string
comes before int
(or any other type) in the operation String
conversion is used and all the rest of the operands will be treated as strings
, and it consists only of a String
concatenation operation.int
comes first in the operation it will be treated as int
, thus addition
operation is used.That's why a + b +" "
gives 7
because String
is in the end of the operation, and for other expressions a + b +" "+ a+b
or ""+ a+b
, the variables a
and b
will be treated as strings
if the come after a String
in the expression.
For further details you can check String Concatenation Operator + in Java Specs.