一起使用String和int时System.out.println的行为 [英] System.out.println behavior when using String and int together
问题描述
考虑以下代码片段-
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);
}
}
以上代码段的输出为-
7
7 34
34
从输出中可以明显看出,如果我们首先在print语句中使用String,那么这些整数将被连接起来.但是,如果我们首先使用整数,那么将添加并显示这些值.
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?
我什至试图查看PrintStream类中println()方法的实现,但无法弄清.
I even tried to look at the implementation of println() method in PrintStream class but could not figure out.
推荐答案
实际上不是由 println()
实现引起的,这是 Java
处理<在处理 Strings
时使用code> + 运算符.
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 operationString
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.
这就是为什么 a + b +"
给出 7
的原因,因为 String
在操作的末尾,对于其他表达式 a + b +" + a + b
或" + a + b
,变量 a
和 b
将如果表达式中的 String
之后出现,则被视为 strings
.
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.
这篇关于一起使用String和int时System.out.println的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!