一起使用String和int时System.out.println的行为 [英] System.out.println behavior when using String and int together

查看:47
本文介绍了一起使用String和int时System.out.println的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段-

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 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.
  • If int comes first in the operation it will be treated as int, thus addition 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 Stringis 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆