Conditionals
Programming Languages · Java Basics · 12 min
Let your program make decisions with if, else and switch.
Comparisons
A comparison asks a yes/no question and gives back a boolean: true or false.
> bigger, < smaller, >= at least, <= at most, == equal, != not equal. (Numbers use ==; Strings use .equals().)
int x = 5;
System.out.println(x > 3); // true
Print whether
ageis at least 18.Print whether
ageis equal to 21.
if and else
if runs a block of code only when its condition is true. else runs when it's false. Exactly one of the two blocks runs.
if (score > 50) {
System.out.println("You win");
} else {
System.out.println("Try again");
}
If
temperatureis greater than 25, printHot day. Otherwise, printNice day.Change
temperatureto18and run again. Now the else block runs.
More choices: else if
Need more than two options? Chain else if. Java checks each condition from the top and runs the first one that's true, then skips the rest.
if (n > 0) {
System.out.println("positive");
} else if (n < 0) {
System.out.println("negative");
} else {
System.out.println("zero");
}
Print
Aifscoreis 90 or more,Bif it's 70 or more, andCotherwise.
And, or, not
Combine conditions with:
&&(and): true only if both sides are true||(or): true if at least one side is true!(not): flips true to false and back
if (hungry && hasFood) {
System.out.println("Eat!");
}
If
ageis at least 18 andhasTicketis true, printCome in.If
ageis under 12 orisHolidayis true, printFree snack.Print
!hasTicket.
switch
switch picks one option by matching a value exactly. Each case is one possible value. default runs when nothing matches.
End each case with break, or Java keeps running into the next case too.
switch (size) {
case 1:
System.out.println("Small");
break;
default:
System.out.println("Other");
}
Write a
switchonday: 1 printsMonday, 2 printsTuesday, 3 printsWednesday, anddefaultprintsSome other day.
Put it together: ticket prices
A cinema charges:
- under 12:
Price: 5 - 65 or older, or a student:
Price: 7 - everyone else:
Price: 12
Use
if,else ifandelseto print the right price forageandisStudent.Change
ageto30andisStudenttotrue. It should still printPrice: 7.