Conditionals and Control Flow

Before this lesson, our code executed from top to bottom, line by line.

Conditional statements add branching paths to our programs. We use conditionals to make decisions in the program so that different inputs will produce different results.

Conditionals have the general structure:

if (condition) { // consequent path } else { // alternative path }

Specific conditional statements have the following behavior:

  • if-then:
    • code block runs if condition is true
  • if-then-else:
    • one block runs if conditions is true
    • another block runs if condition is false
  • if-then-else chained:
    • same as if-then but an arbitrary number of conditions
  • switch:
    • switch block runs if condition value matches case value


Our complete Order program is in the text editor but the main() method is empty.

Create different Order instances and see if you can run the code in all the different conditional blocks!

Folder Icon

Take this course for free

Already have an account?