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?

Jon Skeet
people
quotationmark

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);

people

See more on this question at Stackoverflow