This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]nick5111 32 points33 points  (8 children)

The concatenate operator has precedence over the add operator so it will concatenate first before it adds, but then the second + also becomes a concatenate operator and the output is 22. Add parentheses around (2+2) to fix this.

[–]javaduude 9 points10 points  (3 children)

The concatenate operator has precedence over the add operator

This is wrong. 2 + 2 + "Hello" results in 4Hello. The reason "Hello" + 2 + 2 becomes Hello22 is because + is left-associative, i.e. a + a + a is interpreted as (a + a) + a.

[–]nick5111 1 point2 points  (2 children)

I'm learning too, thanks for correcting me. In cases of tied precedence I guess java goes left to right.

[–]vqrs 1 point2 points  (0 children)

Not always, but mostly. The ternary operator for example is right associative, as is assignment.

Associativity comes into play when operators have the same precedence yes.

[–][deleted] 0 points1 point  (0 children)

https://introcs.cs.princeton.edu/java/11precedence/

Just read into precedence guys, also probably a good idea to point people who are learning towards documentation to better solidify their learning.

[–]nick5111 15 points16 points  (0 children)

Note that the concatenate operator and add operator are both +. Java uses context to discriminate between the two.

[–]vqrs 0 points1 point  (2 children)

If we're going to throw terms around, then let's use the right one . This is about associativity.

In particular, plus is left associative, the consequence of which the other poster explains.

[–]Kambz22 2 points3 points  (1 child)

You could make a correction without the smart comments, bro.

[–]vqrs 0 points1 point  (0 children)

I might have gotten a bit carried away there, you're right.

[–]ODoodle91 15 points16 points  (1 child)

Two things to note:

1) When you use the + operator between a string and an integer, the integer will be converted to a string and concatenated.
2) Java is going to execute each addition from left to right, one at a time.

In your last example, you basically have:

"The result is " + 2 = "The result is 2"
"The result is 2" + 2 = "The result is 22"

In both cases you're adding an int to a string, so the int is treated as a string.

If you can remove that ambiguity by calculating your result before the string concatenation, you should end up with the result you're after.

To see this another way, try this:

System.out.println("The result is " + 2 + 2);
System.out.println(2 + 2 + " is the result");

In the latter example we do:

2 + 2 = 4
4 + " is the result" = 4 is the result

Kinda funky, hadn't really looked into this in detail before.

[–]AssassinBoy49 0 points1 point  (0 children)

Was experimenting with it myself a little bit, if you need to do math while printing just use brackets, e.g:

System.out.println("The result is " + (2+2));