问题
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.
回答1:
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:
- If the
string
comes beforeint
(or any other type) in the operation String conversion is used and all the rest of the operands will be treated asstrings
, and it consists only of aString
concatenation operation. - If
int
comes first in the operation it will be treated asint
, thusaddition
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.
回答2:
It has nothing to do with the implementation of println
. The value of the expression passed to println
is evaluated before println
is executed.
It is evaluated left to right. As long as both operands of +
are numeric, addition will be performed. Once at least one of the operands is a String
, String
concatenation will be performed.
System.out.println(a + b + " ");
// int + int int + String
// addition, concatenation
System.out.println(a + b + " " + a + b);
// int + int int + String Str+Str Str+Str
// addition, concat, concat, concat
System.out.println("" + a + b);
// String+int String+int
// concat, concat
回答3:
First case:
System.out.println(a + b +" ");
In this order, a + b
will first be evaluated as a int sum, then converted to a string when adding the space (the second +
here is for string concatenation).
Second case:
System.out.println(a + b +" "+ a+b);
Here the first part will be int sum operation then converted to a string as we add the space (the 2nd +
is for string concatenation), the rest will be string concatenation as the left operand is already a string.
Third case:
System.out.println(""+ a+b);
Same as 2nd.
Notes:
In order to change this behavior, just add parenthesis to force the int
sum before the string
concatenations.
来源:https://stackoverflow.com/questions/55216552/system-out-println-behavior-when-using-string-and-int-together