1

what is the explanation of this precedence in strings in java?

public class PrecedenceInStrings {

public static void main(String[] args){

int x = 3;
int y = 5;

String s6 = x + y + "total";
String s7 = "total " + x + y;
String s8 = " " + x + y + "total";

System.out.println(s6 + "\n" + s7 + "\n" + s8);
}
}

output:

8total

total 35

35total

0

1 Answer 1

1

Java compiler processes operators + in your expressions left to right. When it comes to the first + in

x + y + "total"

it sees ints on both sides, so it performs an addition. When Java compiler processes the second +, it sees an int and a String, and interprets the operator as string concatenation.

In your second and third expressions the left-hand side of the + operator is a string, so all operators get interpreted as concatenations.

If you want to force a specific order of operations, use parentheses. For example, if you would like to get the total in your third example, parenthesize the addition, like this:

String s8 = " " + (x + y) + "total";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.