Java – the difference/ advantage of doing double assignment

javavariables

Is there any advantage / is it a bad practice in Java to do the below

x = x = 5

I saw it in one of my peers code and I was surprised why he would do double assignment?

Is this something that is same as x = 5 or if x = x= 5 makes a difference?

Best Answer

Is there any advantage/ is it a bad practice to do the below

x= x = 5

You haven't specified the language, but in most C-like languages the value of an assignment is the value being assigned. That is, the value of the expression x = 5 is 5, and the expression you're asking about is essentially the same as doing:

x = 5;
x = 5;

There's no value in the extra assignment, so no reason to do it.

Now, what you do sometimes see is the assignment of two (or more) variables to some value at the same time, like this:

x = y = 5;

In this case, you're assigning 5 to y, and then assigning the value of that expression (again, 5) to x. This ensures that both x and y get the same value.

Another possibility is that one of the assignments was intended to be a comparison, with the result assigned to the variable being compared:

x = x == 5;

This isn't a double assignment, it's assignment of the boolean expression x == 5 to x. That is, if the value of x is 5 before the expression, x will get the value of true (some non-zero integer); if x is not 5, x will be set to false (i.e. 0).