Java Conditionals

Why Use Conditionals?

Conditional statements let your program make decisions. For example, you can run different code depending on whether a value is true or false.

if, else if, and else Statements

Use these statements to test one or more conditions and execute different blocks of code depending on the result.

  • if: runs if the condition is true
  • else if: checks another condition if the first is false
  • else: runs if none of the above are true
Loading...
Output:

Nested if Statements

You can place if statements inside other if statements to test multiple layers of logic.

Loading...
Output:

switch Statement

The switch statement is used as a cleaner alternative to multiple if-else conditions when checking a single variable against multiple possible values.

Each case matches a specific value. If a match is found, that block executes. Use break to exit the switch after a match. If no case matches, the default block (optional) runs.

This is useful when comparing discrete values like numbers, enums, or strings (Java 7+).

Loading...
Output:

Relational & Logical Operators

These are commonly used in conditionals:

  • ==, !=, >, <, >=, <=
  • && (AND), || (OR), ! (NOT)
Loading...
Output:

Practice Question

What will this print?

Loading...
Output:

Hint: Both conditions are true, so the if block runs.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic