Like with normal math, there is some ordering on execution of infix symbols. At school I learnt BIDMAS or BODMAS (depending on who was teaching it) although you may also know of PEDMAS. Java follows the same order of execution for the infix symbols as mathematics (see this refference).
This means that the *
symbol is evaluated before the +
symbol as it has a higher priority (or more technically accurate to programming, a higher precedence). When using infix notation, java typically uses the type of the first element as the type for the output, so a + b
will yeild a result of the same type as a
. In this way, this is why you get string concatenation with your first example.
When java evaluates, it will group the infix notation into pairs and use this same rule so:
System.out.println("Result"+2+3*5)
becomes:
System.out.println((("Result"+2)+(3*5)))
If you pay careful attention to the brackets I have put in, you can see the order of execution quite clearly. Either the concatenation of "Result"
and 2
is done first or the multiplication of the 3
and 5
- either way this would not affect the result. After this, Result2
is concatenated with 15
.
If for example, you wanted to force order of execution, then brackets rule over all others so you could easily make your first example output Result9
by the following addition of brackets:
System.out.println("Result"+(2+3+4))
The safest thing to do however, is always use brackets, that way there will be no discrepancy as to what the order of evaluation is.
For a full guide on Operator Precedence you can view the Java Documentation on Operators