Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - assigning two expressions to a single variable simultaneously

Tags:

java

I've just finished my first year of Java and I've been looking at the JDK source code as an exercise.

I came across something I've never encountered before where there were two assignments to the same variable in the same statement.

e.g.

variable = expression = expression;

What exactly is going on here? Is this a fairly common thing? What is the purpose of a double assignment?

Thanks a lot -Mike

like image 382
kontrarian Avatar asked Dec 22 '22 22:12

kontrarian


1 Answers

variable1 = variable2 = expression;

Can be written as

variable2 = expression;
variable1 = variable2;

This is because equal signs are evaluated from right to left after everything else is evaluated (basically the lowest operation in order of operation).

This is generally seen as tacky, and I wouldn't advise it.

like image 135
bwawok Avatar answered Jun 12 '23 21:06

bwawok