Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference of x=x+3 and x+=3? Why one needs type cast and the other does not?

Question :

char x = 'a'; 
x += 3; // ok  
x = x + 3; // compile time error
like image 589
user845932 Avatar asked Jul 27 '11 13:07

user845932


People also ask

What does x += y mean?

x++ is postfix increment and y is postfix decrement, postfix means the values of x and y will be used first in the expression after that increment/decrement operation will be applied. eg : int x=5,y=4; int z=x++*y--; //value of z will be 20 (5*4) //value of x will be 6 and value of y will be 3.

What does x += 1 mean in Java?

It's the Addition assignment operator. Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

What does += mean in Java code?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable.

Is X ++ the same as X 1?

You probably learned that x++ is the same as x = x+1 .


1 Answers

Because x += 3 is equivalent to x = (char)(x+3), while x + 3 is default to int operation, assign an int to char must cast.

From the JLS specification : 15.26.2 ,

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T may be either an identity conversion (?.1.1) or a narrowing primitive conversion (?.1.3).

like image 183
Saurabh Gokhale Avatar answered Sep 18 '22 13:09

Saurabh Gokhale