In Java, statements can be executed conditionally through IF…ELSE and SWITCH structures. The IF statement evaluates a Boolean expression; if true, an associated block of code is executed; otherwise, the following ELSE block is executed (Farrell, 2014). Common mistakes when writing an IF…ELSE statements include errors in syntax, such as putting a semicolon after the Boolean expression or using the assignment operator = instead of the equivalency operator == (Farrell, 2014). Another issue can be caused by attempting to compare classes without writing special methods to do so (Farrell, 2014). IF statements allow programs to follow complex branching logic that is required for modern applications.
A SWITCH statement is similar to a series of nested IF…ELSE checks. It evaluates one variable against exact integer, character, or string values (Farrell, 2014). The SWITCH statement is a convenience feature that offers improved code legibility compared to a series of nested IF…ELSE structures (Farrell, 2014). It can be used when a reasonably low number of outcomes depend on a single valid variable containing a specific value (Farrell, 2014). In other cases, nested IF…ELSE structures are preferable to a SWITCH structure.
To facilitate working with conditional logic, logical operators AND (&&), OR (||), and NOT (!) can be used. The && operator is useful when comparing a value to a range, such as checking whether a user’s age is between 13 and 18 years for displaying age-restricted content. The || operator can be used to check whether at least one qualifier is true. For example, a student taking at least one from a list of subjects might be eligible for additional library access. Finally, a ! operator inverts a Boolean expression, which is useful in cases such as checking whether one account’s balance is sufficient for a transaction.
Reference
Farrell, J. (2014). Java Programming (7th ed.). Boston, MA: Cengage Learning.