简体   繁体   中英

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

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. 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 .

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
  • adds 90 and "Hello" to yield "90Hello"
  • adds "90Hello" and 50 to yield "90Hello50"
  • adds "90Hello50" and 50 to yield "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.

Because Java will concat your string from left to right. 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. then "90hello" is str and it will contact with 50 which is int and the result as I said will be str and continue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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