Conditionals
Our programs so far have run sequentially - one line after another from top to bottom. But there are ways to alter the order in which our code executes. One is with if-statements.
We can use if-statement to control whether or not certain code runs. In an if-statement, if the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped.
if (condition) {
// Replace with code
}
// Then the program would resume the regular flow of code
What if you want to pick between two possibilities? The following flowchart demonstrates that if the condition is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed, before resuming the regular flow of code.
if (condition) {
// Replace with code that would happen if the condition is true
} else {
// Replace with code that would happen if the condition is false
}
// Then the program would resume the regular flow of code
If there are to be more than 2 possibilities, we can combine “else” and “if” to “else if” to create 3 or more possibilities. In this case, the computer would evaluate each condition from first to last, entering only the first condition that is true. If none are true, Java would default to “else”, if it is part of the structure.
if (condition) {
// Code given that the first if is true
} else if (2nd condition) {
// Code given that the second if is true
} else if (3rd condition) {
// Code given that the third if is true
} // You can have as many else ifs as you want
Recall from 1-way if-statements that an if-statement does NOT require an “else” portion.
If you include one though, it’ll always be the last block.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input your name: "); String name = sc.nextLine().toLowerCase(); if (name.contains("w")) { System.out.println("8% of American names contain a w"); } System.out.println("Cool name!"); } } |
When writing if-statements, we need to be able to write a condition that can either be “true” or “false”. These types of statements are called “boolean expressions”.
Operation |
What is it? |
Example |
== |
Tests if two things are equal |
var1 == 4 |
!= |
Tests if two things are not equal |
var1 != 4 |
> and < |
Tests if one is greater or less than |
var1 < 4 |
>= and <= |
Tests if one is greater than or equal to, or less than or equal to |
var1 >= 4 |
Remember: One = sign changes the value of a variable. Two == equal signs are used to test if a variable holds a certain value, without changing its value!
Scanner sc = new Scanner(System.in);
System.out.print("Input a number: "); int num = sc.nextInt();
if (num > 10) { System.out.println("Too high!"); } else if (num < 10) { System.out.println("Too low!"); } else { System.out.println("Yes, that's right!"); } |
When you use the == comparison operator with Strings, the code may not behave how you’d expect. For instance:
Scanner sc = new Scanner(System.in);
String userInput = sc.nextLine(); // Assume the user inputs "hello"
if (userInput == "hello") { System.out.println("equal!"); } else { System.out.println("not equal!"); } |
not equal! |
“not equal” will always be printed in this scenario. This is because of the way variables and data are stored. The userInput variable is pointing not to the actual, literal String “hello”, but the place in memory where the String “hello” has been stored by your program.
So when you compare the variable userInput, which is pointing to a memory address, to the actual String “hello”, it will always say they are not equal. You’re comparing apples to oranges.
Therefore, with Strings, you will almost always want to use the equals() method to compare Strings, which will compare the String that is stored at the memory address, rather than the memory address itself.
If you’re just testing for equality, a switch-statement could be used in place of an if-statement. A switch statement will test equality for a given variable, and will perform defined code depending on what the variable is equal to.
switch (variable) {
case value1:
// Replace with code that would happen if variable == value1
break;
case value2, value3:
// Replace with code that would happen if variable == value2
// OR if variable == value3
// As many cases as you need could be added
break;
default:
// Replace with code that would happen if no cases are true
// default is optional to include
}
// Then the program would resume the regular flow of code
Things to keep in mind when using switch-statements:
String day = "Friday"; switch (day) { case "Monday": System.out.println("Start of the week!"); break; case "Saturday": System.out.println("The weekend begins!"); break; default: System.out.println("Just another day..."); } |
Use && as a logical and to join two boolean expressions and your if-statement code will only be executed only if both are true.
What if you want to go out and your parents say you can go out if you clean your room and do your homework?
public class Main { public static void main(String[] args) { boolean cleanedRoom = true; boolean didHomework = false;
if (cleanedRoom && didHomework) { System.out.println("You can go out"); } else { System.out.println("Sucks to suck"); } } } |
Sucks to suck |
In English, we often use an exclusive-or like in the sentence “do you want to be player 1 or player 2?”, where you can’t be both player 1 and player 2. In programming, the or-operator is an inclusive-or which means that the whole expression is true if either one or the other or both conditions are true.
Maybe your parents might say you can go out if you can walk or they don’t need the car.
public class Main { public static void main(String[] args) { boolean walking = false; boolean carIsAvailable = false;
if (walking || carIsAvailable) { System.out.println("You can go out"); } else { System.out.println("womp womp"); } } |
womp womp |
With numerical values, the or (||) operator is often used to check for error conditions on different ends of the number line, while the and (&&) operator is often used to see if a number is within a range.
int score = 10; // Checking if the score IS NOT within valid bounds of 0 to 100 if (score < 0 || score > 100) { System.out.println("Score has an invalid value."); } // Checking if the score IS within valid bounds of 0 to 100 if (score >= 0 && score <= 100) { System.out.println("Score is in the range 0-100"); } |
The not (!) operator can be used to negate a boolean value. We’ve seen ! before in != (not equal). If you use ! in expressions with && and ||, be careful because the results are often the opposite of what you think it will be at first.
The code below says if homework is not done, you can’t have fun.
public class Main { public static void main(String[] args) { boolean homeworkDone = false;
if (!homeworkDone) { System.out.println("Sorry, no fun for you!!"); } } |
Sorry, no fun for you! |
NOTE: In Java, ! will be executed before &&, and && will be executed before ||, unless there are parentheses. Anything inside parentheses is executed first.
We can put if-statements within if-statements. These are called nested if-statements.
For example, the code below checks if there is an “a” and an “e” using nested if-statements.
public class Main { public static void main(String[] args) { String word = "pear";
if (word.contains("a")) { if (word.contains("e")) { System.out.println("Lots of vowels!"); } } } } |
But with a &&, the code below could achieve the same goal:
String word = "pear";
if (word.contains("a") && word.contains("e")) { System.out.println("Lots of vowels!"); } |
So why would you use a nested if-statement over the && operator? Well, there may be code you’d like to execute between checks. For example:
String word = "pear"; if (word.contains("a")) { System.out.println("The letter \"a\" is pretty common."); if (word.contains("e")) { System.out.println("There's also \"e\"? Lots of vowels!"); } } |