Ch 6 · Conditional Statements · Java

Topic 6 of 13 in Java — Complete Tutorial (Beginner) — 3 lessons.

if / else if / else

A conditional statement lets your program take different actions depending on whether a condition is true. You write if, then a condition in round brackets, then a block of code in curly braces that runs only when the condition is true. Add more options with else if, each with its own condition, and a final else as the catch-all. Java checks the conditions top to bottom and runs the first true one, skipping the rest.

The switch Statement

When you want to compare one variable against many specific values, a switch statement is cleaner than a long chain of else ifs. It evaluates the value once and jumps to the matching case. Classic switches need a break after each case to stop "falling through" to the next. Modern Java also offers a neat arrow form (case 5 ->) that needs no break.

The Ternary Operator

The ternary operator is a compact, one-line version of a simple if-else. It has three parts: condition ? valueIfTrue : valueIfFalse. Read the ? as "then" and the : as "otherwise". Use it when the choice is simple and produces a single value; for anything complex, a normal if/else is clearer.

All topics in Java Beginner

  1. Introduction to Programming & Java
  2. Your First Java Program
  3. Variables — Your Data Containers
  4. Data Types — Kinds of Values
  5. Operators & Expressions
  6. Conditional Statements
  7. Loops & Iterations
  8. Methods
  9. Arrays & Lists
  10. Objects & Classes
  11. Strings — Working with Text
  12. Exception Handling
  13. Mini-Projects & Practice