1

as far as I understand x+=1 works as x=x+1, but why it doesn't work in String?

String str = "";
str = str + null + true; // fine
str += null + true; // Error message: The operator + is undefined for the argument type(s) null, boolean 
0

1 Answer 1

5

In Java, expression are evaluated from left to right. Thus

str = str + null + true;

is the same as

str = (str + null) + true;

and null and true are implicitly converted to Strings. This works because in str + null, the compiler knows that str is a String and converts null to a String. This is possible because every value can be converted to a String in Java. By the same line of argumentation, the compiler knows that (str + null) is a String and thus coverts true to a String.

On the other hand,

str += null + boolean;

is equivalent to

str = str + (null + boolean);

hence, null + boolean is evaluated first. Since the operator + is not defined for types null, boolean, a compiler-error is generated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.