Guide to Object-oriented Programming With Java (University at Buffalo Version)
Chapter 8: Java Conditionals
Java conditionals provide a way to execute a statements or statements based on whether some condtion is met or not met.
Java if/else
Conditional
The if
statement allows you to test whether some condition is true or false. If the result of the test is true then the statement(s) between the first {
and }
are executed. If the result is false the then statement(s) between the else {
and }
are executed. For example:
// if-then-else statement
if (accountBalance > 100) {
System.out.println("Safe balance.");
} else {
System.out.println("Warning: Low balance.");
}
if/else
Statements
<terminated>
Warning: Low balance.
if/else
OutputThe if/else if
Conditional.
You can also useif
to test whether some other condition if the result of the first if
test is false
. For example:
// if-then-elseif statement
if (accountBalance > 100) {
System.out.println("Safe balance.");
} else if (accountBalance < 100) {
System.out.println("Alert: Negative balance.");
}
} else {
System.out.println("Warning: Low balance.");
}
if/else
Statements
<terminated>
Alert: Negative balance.
if/else
OutputJava switch
Conditional
The switch
statement allows you to test whether some condition is met or not met. If the parameter that is passed to the switch
statement is equal to any of the case
statements then the statement(s) between that case:
statement and break
statement are executed. If the parameter does not match any of the case
statements then the tatements after the default:
statement(s) are executed. For example
Sring myName = "Jim";
// switch statement using a string
switch (myName) {
case "Alex":
initial = 'A';
case "Jim":
initial = 'J';
case "Stan":
initial = 'S';
break;
default:
initial = '?';
}
System.out.println("My Name is " + myName + " and my first initial is " + initial + ".");
switch
Statement Using a String
<terminated>
My name is Jim and my first initial is J.
switch
Using a String Outputint lastDay;
boolean leapYear = false;
Sring[] monthsArray = { "January", "February", "March", "April", "May", "June", "July",
; "August", "September", "October", "November", "December" };
// switch statement using a number
switch (month) {
case 1:
lastDay = 31;
break;
case 2:
if (leapYear == true) {
lastDay = 29;
} else {
lastDay = 28;
}
break;
case 3:
lastDay = 31;
break;
case 4:
lastDay = 30;
break;
case 5:
lastDay = 31;
break;
case 6:
lastDay = 30;
break;
case 8:
lastDay = 31;
break;
case 8:
lastDay = 31;
break;
case 9:
lastDay = 30;
break;
case 10:
lastDay = 31;
break;
case 11:
lastDay = 30;
break;
case 12:
lastDay = 31;
break;
default:
lastDay = 0;
}
System.out.println("Month " + monthsArray[month - 1] + " has " + lastDay + " days.");
switch
Statement Using a Number
<terminated>
Month April has 30 days
switch
Statement Using a Number OutputLet's get started with a Conditionals program!