We have been seeing programs which consist of a list of statements, one after another, where the "flow of control" goes from one line to the next, top to bottom, and so on to the end of the list of lines. There are more useful ways of breaking up the "control flow" of a program. Java has several conditional statements that let the programmer do things based on conditions in the data.
The first conditional statement is the if statement.
if (something-is-true) {
doSomething;
}Here are a few simple examples.
if (speed > speedLimit) {
driver.getsATicket();
}
if (x <= -1) {
System.out.println("Cannot have negative numbers!");
}
if (account.balance >= amountRequested) {
subtract(account, amountRequested);
produceCash(amountRequested);
printReceipt(amountRequested);
}Java also has an else part to the if statement. When the if condition is False, the else part gets run. Here, if the account doesn’t have enough money to fulfill the amountRequested, the else part of the statement gets run, and the customer gets an insufficient funds receipt.
if (account.balance >= amountRequested) {
// let customer have money
} else {
printReceipt("Sorry, you don't have enough money in your account!")
}Java can also "nest" if statements, making them very flexible for complicated situations. You can also see here how curly-braces make it clear what statements get executed based on which case or condition is true.
String timeOfDay = "Afternoon";
if (timeOfDay.equals("Morning")) {
System.out.println("Time to eat breakfast");
eatCereal();
} else if (timeOfDay.equals("Afternoon")) {
System.out.println("Time to eat lunch");
haveASandwich();
} else {
System.out.println("Time to eat dinner");
makeDinner();
eatDinner();
doDishes();
}Notice how this becomes a 3-way choice, depending on the timeOfDay.
Exercise: Age Verification
Write code to check if a user is old enough to drink.
-
if the user’s age is under 18. Print out "Cannot party with us"
-
Else if the user’s age is 18 or over, Print out "Party over here"
-
Else print out, "I do not recognize your age" You should use an if statement for your solution!
Finally, make sure to change the value of the age variable in jshell, to output different results and test that all three options can happen. What do you have to do to make the else clause happen?
int userAge = 17;
if (userAge < 18) {
System.out.println("Cannot party with us");
} else if (userAge >= 18) {
System.out.println("Party over here");
} else {
System.out.println("I do not recognize your age");
}If statements are one of the most commonly used statements to express logic in a Java program. It’s important to know them well.
Try these exercises in jshell to practice if statements and conditional logic:
Exercise 1: Simple If Statements
Create a temperature checking program:
int temperature = 75;
if (temperature > 80) {
System.out.println("It's hot outside!");
}
if (temperature < 60) {
System.out.println("It's cold outside!");
}
if (temperature >= 60 && temperature <= 80) {
System.out.println("Perfect weather!");
}
System.out.println("Current temperature: " + temperature + "°F");Try changing the temperature value to test different conditions.
Exercise 2: If-Else Statements
Create a grade calculator:
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
System.out.println("Score: " + score);
System.out.println("Grade: " + grade);
if (score >= 70) {
System.out.println("Passing grade!");
} else {
System.out.println("Need to retake the test.");
}Exercise 3: Nested If Statements
Create a movie recommendation system:
int age = 16;
String movieType = "action";
boolean hasParent = false;
System.out.println("Age: " + age + ", Movie type: " + movieType);
if (age >= 18) {
System.out.println("Can watch any movie");
} else {
if (movieType.equals("kids")) {
System.out.println("Can watch kids movies");
} else if (movieType.equals("teen") && age >= 13) {
System.out.println("Can watch teen movies");
} else if (hasParent) {
System.out.println("Can watch with parent supervision");
} else {
System.out.println("Cannot watch this movie");
}
}Exercise 4: Complex Conditions
Create a login validation system:
String username = "admin";
String password = "secret123";
boolean accountLocked = false;
int loginAttempts = 2;
if (accountLocked) {
System.out.println("Account is locked. Contact administrator.");
} else if (loginAttempts >= 3) {
System.out.println("Too many failed attempts. Account locked.");
} else if (username.equals("admin") && password.equals("secret123")) {
System.out.println("Login successful! Welcome, " + username);
} else {
System.out.println("Invalid username or password.");
System.out.println("Attempts remaining: " + (3 - loginAttempts - 1));
}