LEARN JAVA : CONDITIONALS AND CONTROL FLOW

CONDITIONALS AND CONTROL FLOW


Java:Conditonal and Control Flow

If-Then Statement


The if-then statement is the most simple control flow we can write. It tests an expression for truth and executes some code based on it.
if (flip == 1) { System.out.println("Heads!"); }
  • The if keyword marks the beginning of the conditional statement, followed by parentheses ().
  • The parentheses hold a boolean datatype.
For the condition in parentheses we can also use variables that reference a boolean, or comparisons that evaluate to a boolean.
The boolean condition is followed by opening and closing curly braces that mark a block of code. This block runs if, and only if, the boolean is true.
boolean isValidPassword = true; if (isValidPassword) { System.out.println("Password accepted!"); } // Prints "Password accepted!" int numberOfItemsInCart = 10; if (numberOfItemsInCart > 12) { System.out.println("Express checkout not available"); } // Nothing is printed.
If a conditional is brief we can omit the curly braces entirely:
if (true) System.out.println("You're my Soul :)");

Note: Conditional statements do not end in a semicolon.

If-Then-Else

We’ve seen how to conditionally execute one block of code, but what if there are two possible blocks of code we’d like to execute?
Let’s say if a student has the required prerequisite, then they enroll in the selected course, else they’re enrolled in the prerequisite course instead.
We create an alternate conditional branch with the else keyword:
if (hasPrerequisite) { // Enroll in course } else { // Enroll in prerequisite }
This conditional statement ensures that exactly one code block will be run. If the condition, hasPrerequisite, is false, the block after else runs.
There are now two separate code blocks in our conditional statement. The first block runs if the condition evaluates to true, the second block runs if the condition evaluates to false.
This code is also called an if-then-else statement:
  • If condition is true, then do something.
  • Else, do a different thing.

If-Then-Else-If

The conditional structure we’ve learned can be chained together to check as many conditions as are required by our program.
Imagine our program is now selecting the appropriate course for a student. We’ll check their submission to find the correct course enrollment.
The conditional statement now has multiple conditions that are evaluated from the top down:
String course = "Theatre"; if (course.equals("Biology")) { // Enroll in Biology course } else if (course.equals("Algebra")) { // Enroll in Algebra course } else if (course.equals("Theatre")) { // Enroll in Theatre course } else { System.out.println("Course not found!"); }
The first condition to evaluate to true will have that code block run. Here’s an example demonstrating the order:
int testScore = 72; if (testScore >= 90) { System.out.println("A"); } else if (testScore >= 80) { System.out.println("B"); } else if (testScore >= 70) { System.out.println("C"); } else if (testScore >= 60) { System.out.println("D"); } else { System.out.println("F"); } // prints: C
This chained conditional statement has two conditions that evaluate true. Because testScore >= 70 comes before testScore >= 60, only the earlier code block is run.

Note: Only one of the code blocks will run.

Switch Statement

An alternative to chaining if-then-else conditions together is to use the switch statement. This conditional will check a given value against any number of conditions and run the code block where there is a match.
Here’s an example of our course selection conditional as a switch statement instead:
String course = "History"; switch (course) { case "Algebra": // Enroll in Algebra break; case "Biology": // Enroll in Biology break; case "History": // Enroll in History break; case "Theatre": // Enroll in Theatre break; default: System.out.println("Course not found"); }
This example enrolls the student in History class by checking the value contained in the parentheses, course, against each of the case labels. If the value after the case label matches the value within the parentheses, the switch block is run.
In the above example, course references the string "History", which matches case "History":.
When no value matches, the default block runs. Think of this as the else equivalent.
Switch blocks are different than other code blocks because they are not marked by curly braces and we use the break keyword to exit the switch statement.
Without break, code below the matching case label is run, including code under other case labels, which is rarely the desired behavior.
String course = "Biology"; switch (course) { case "Algebra": // Enroll in Algebra case "Biology": // Enroll in Biology case "History": // Enroll in History case "CS": // Enroll in CS default: System.out.println("Course not found"); } // enrolls student in Biology... AND History and Theatre!

Review

We use conditionals to make decisions in the program so that different inputs will produce different results.
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

No comments:

Powered by Blogger.