Functions and Conditions

In this chapter, we will discuss programming flow logic and various ways to organize your code. You will learn about functions, if-else, and switch statements.

Updated

Introduction to Functions

  1. Introduction to Functions: an overview (Novice): When you keep repeating the same lines of code, you can turn them into a function, one reusable block you call by name.
  2. Practice: The need for functions (Novice): Print the scores of five football teams by copying and pasting the same code, and see why repeated code is a problem.
  3. Organizing code into functions (Apprentice): Learn the four parts of a function (name, parameters, return type and body), and how to call one and keep the value it returns.
  4. Practice: Creating Functions (Apprentice): Replace the copied team-score code with one displayTeamScores function that takes each team's rank, name and scores as parameters.

Conditional Logic

  1. If (Novice): Use if, if-else and if-else if-else to run a block of code only when a condition is true, or to pick one block out of several.
  2. Multiple Conditions (Apprentice): Combine conditions with && (and) and || (or), and use parentheses to group them so the if means what you intend.
  3. Switch (Apprentice): The switch statement provides a more readable and efficient way to execute different code blocks based on the value of a single variable.
  4. Switch Expressions (Apprentice): Java's arrow switch never falls through, lets one case match several values, and can give back a value you store in a variable, with no break to forget.