简体   繁体   English

为什么整数和字符串的连接表现出这样的行为?

[英]Why does a concatenation of integers and strings behave like this?

This code: 这段代码:

public void main(String[] args)
{
    String s1 = 50+40+"Hello"+50+50;
    System.out.println(s1);
}

Gives output of: 90Hello5050 输出为: 90Hello5050

Why? 为什么?

It's just a matter of precedence and associativity. 这只是优先级和关联性的问题。 Your code is equivalent to: 您的代码等效于:

String s1 = (((50 + 40) + "Hello") + 50) + 50;

So that's: 所以那是:

String s1 = ((90 + "Hello") + 50) + 50;

which is: 这是:

String s1 = ("90Hello" + 50) + 50;

which is: 这是:

String s1 = "90Hello50" + 50;

which is: 这是:

String s1 = "90Hello5050";

If you wanted 90Hello100 you should use brackets to make it explicit. 如果您想要90Hello100 ,则应使用方括号将其明确显示。 I'd write it as: 我将其写为:

String s1 = (50 + 40) + "Hello" + (50 + 50);

According to the Java Language Specification, Section 15.7, "Evaluation Order" , operators in Java are evaluated from left to right . 根据Java语言规范的第15.7节“评估顺序” ,Java中的运算符从左到右进行评估。

That means that your concatenation is evaluated like it was written as 这意味着您的串联被评估为与

String s1 = (((50+40)+"Hello")+50)+50;

That's why it 这就是为什么

  • adds 50 and 40 to yield 90 加50和40得到90
  • adds 90 and "Hello" to yield "90Hello" 将90和“ Hello”相加得到“ 90Hello”
  • adds "90Hello" and 50 to yield "90Hello50" 添加“ 90Hello”和50以产生“ 90Hello50”
  • adds "90Hello50" and 50 to yield "90Hello5050" 将“ 90Hello50”和50相加得到“ 90Hello5050”

In general, when you have a binary operation (like "+" in this case) that can be applied to a String and the computation involves a String , the other operand is converted into a String as well. 通常,当您具有可以应用于String的二进制运算(在这种情况下为“ +”)并且计算涉及String ,另一个操作数也将转换为String

Because Java will concat your string from left to right. 因为Java将从左到右连接您的字符串。 and it will add 50 and 40 with each other because they are int and then concat that to "hello" string and result is str because int and str will be str output. 它将彼此相加50和40,因为它们是int ,然后将其连接到“ hello”字符串,结果是str因为intstr将是str输出。 then "90hello" is str and it will contact with 50 which is int and the result as I said will be str and continue. 然后“ 90hello”为str ,它将与50的int接触,如我所说,结果将为str并继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM