I am facing something strange here. Please help me understand if I am missing something. My if condition was supposed to be:
if(configuredPdf == true)
An assignment expression's result is always the value that was assigned, including when assigning to a boolean. This is covered by JLS§15.26:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.
So yes, configuredPdf = true
assigns true
to configuredPdf
, and the result of that expression is true
.
Similarly, x = y = 5;
assigns 5
to y
, and the result of y = 5
is 5
, which is then assigned to x
.
Fundamentally, what you wanted was:
if (configuredPdf)
There's never any need to compare a boolean variable with true
or false
, just use the if (theVariable)
(for comparing with true
) or if (!theVariable)
(for comparing with false
). Getting in that habit will protect you from inadvertent assignment.
The only time actually comparing boolean values is useful is when they're both variables, e.g. if (thisFlag == thatFlag)
or if (thisFlag != thatFlag
).
To avoid accidental assignment in that situation, either:
Use a linter that checks for this
"double bang" the first flag:
if (!!thisFlag == thatFlag)
...although as you pointed out if you can accidentally type =
instead of ==
, presumably you can accidentally type !
instead of !!
:-)
Use an old C idiom (this is what I use):
if (!thisFlag == !thatFlag)