Compound Boolean Expressions

Understand the details of compound boolean expressions.

Nested conditions

The word nested means one thing inside another. Think about this term in real life.

The phrase above states that you can go outside if it’s raining, only if you have an umbrella. To go outside, there are two conditions. ‘If it rains’ is the first condition, and ‘having an umbrella’ is the second condition, nested inside the first condition. If it never rains, we won’t check for an umbrella. If it rains, then we have to check for an umbrella before going out. If we don’t find an umbrella, we cannot go outside.

Combining multiple boolean expressions

In terms of programming, an if statement inside another if statement creates an impression of the compound boolean expression.

Here is its syntax:

if (boolean expression) 
{
  if (boolen expression) 
  {  // nested if
    statement(s)
  }
}

Example

For example, we only want to greet a person whose first name is ‘John’ and whose last name is ‘Christopher’.

Run the program below to see how it’s done.

Press + to interact
class NestedIf
{
public static void main(String args[])
{
String firstName = "John";
String lastName = "Christopher";
if (firstName == "John")
{
if (lastName == "Christopher") // Nested if
{
System.out.println("Hi, John Christopher!");
}
}
}
}

Initially, we declare two String variables: firstName and lastName. Look at line 8. We add a condition next to an if statement. The condition is checking whether or not firstName is “John”. If yes, the condition will evaluate ...