=
is assignment operator,==
is comparison operator.
But assignment operator
x = y
not only assigns value from y
to variable x
, but it also returns that value.
Thanks to that we can write code like
x = y = z = 1;
//equivalent of:
x = (y = (z = 1));
(although it is not recommended as it can be confusing, especially for new Java programmers)
As you see 1
is first assigned to variable z
, then expression z = 1
returns 1 which can be assigned to variable y
. Then again assigning 1 to y
returns 1 which can be assigned to variable x
.
Because of that returning mechanism it is possible to write code like if (b = true)
since true
will be assigned to b
and then returned. Since if(..)
expected boolean for its condition, and found one code compiled fine.
In other words if(b=true){...}
is very similar to if(true){b=true; ...}
. This means that such if
will always execute code from true
branch (since that is what we ware assigning to b
).
BONUS: How to prevent this typo?
-
omit
==true
and==false
parts.- In case of
if(b==true)
we can writeif(b)
since(b == true)
will always give same result as already stored inb
. - In case of
if(b==false)
we can writeif(!b)
.
- In case of
-
use Yoda conditions
if(true == b){..}
where value is used before/on left side and variable on right side of==
.
Even if by mistake we will write=
instead of==
we will end up withtrue = b
which will end up as compilation error since we can’t assign anything to value liketrue
(just like we can’t compile2=3;
which would attempt to assign 3 to 2 which makes no sense). We can only assign values to variables.