Avoiding Common Mistakes
Following are the common beginner mistakes to avoid when declaring or using a boolean variables in apex.
Assuming default values
It is a common misconception that boolean variables are automatically initialized to false
. However, this is not the case — in Apex, all data types are initialized to null
when declared.
Assigning incorrect values
Boolean values can only accept true
or false
, and the following assignments result in compilation errors.
Don't do this
Do this
Note
Any value enclosed in single quotes ('') is treated as a string in apex.
Comparison & Assignments
When comparing two boolean variables, always use the ==
operator instead of =
. The =
operator is only used for assignments (i.e., assigning a value to a variable). Using the =
operator in a conditional statement will result in a compilation error.
Don't do this
Do this
Redundant comparison
Conditional statements always expect an expression to evaluates to true or false. But beginners commonly use the ==
comparison operators to compare with true or false, which is redundant. Using the boolean variable alone is sufficient for a conditional statement.
Don't do this
Do this
Negating booleans
When comparing a boolean variable to a negative value, always use the negation operator (!)
rather than comparing it to false
.