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 is an expression which returns the value you assigned. e.g. a = b = true
will assign true
to a
and b
.
The reason boolean
type was added was to avoid this sort of bug. In C for example you can write
if (a = 1)
and anything non-negative is true.
While you can still make a mistake with boolean types, instead of writing
if (a == true)
if (b == false)
you can write
if (a)
if (!b)
A more common example is
for(String line; ((line = br.readLine()) != null;) {
// process the line.
}
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)
configuredPdf
must be a boolean for if(configuredPdf = true)
to compile.
configuredPdf = true
will assign true
to configuredPdf
and thus if
will succeed.
Yes, configuredPdf = true
assigns true
to your variable and returns true
. Therefore if (configuredPdf = true)
is a valid syntax even though it's usually a bug.
It's safer to use if (configuredPdf)
to avoid this kind of typo.
What is happening is when the compiler comes to the if condition in your code, it assigns 'configuredpdf' to be true. Thus the condition
if(configuredpdf = true)
Becomes true and the loop executes successfully. However, the problem arises when we DON'T want this loop to be true. At that time when, for a given input, the compiler parses the if condition, it forcibly becomes true and executes the code written in if condition executes even if the data entered does not agreeing. That is why you will find that your code has a bug at the if condition.