Intermediate Java
Jim White
Java Developer
if-else
statementsif (bonus == 10000) {
System.out.println("Let's buy a car!");
} else if (bonus == 5000) {
System.out.println("Let's take a trip!");
} else if (bonus == 1000) {
System.out.println("Let's save!");
}
switch (expression) {
case value1: // if (expression == value1)
// statements
case value2: // if (expression == value2)
// statements
// use as many case statements as needed
}
char direction = 'N';
switch (direction) {
case 'E':
System.out.println("We are headed east.");
case 'S':
System.out.println("We are headed south.");
case 'W':
System.out.println("We are headed west.");
case 'N':
System.out.println("We are headed north."); // This would be printed
}
char direction = 'W';
switch (direction) {
case 'E':
System.out.println("We are headed east.");
case 'S':
System.out.println("We are headed south.");
case 'W':
System.out.println("We are headed west."); // This would be printed
case 'N':
System.out.println("We are headed north."); // This would also be printed
}
break
allows combining multiple cases together:
char direction = 'N';
switch (direction) {
case 'E':
case 'W':
System.out.println("We are headed east or west.");
break;
case 'S':
case 'N':
System.out.println("We are headed south or north.");
break;
}
We are headed east or west.
default
case can be added to the end of a switchdefault
must be the last case in a switchdefault
is a way to have an "all other values" casechar direction = 'z';
switch (direction) {
case 'E':
case 'W':
System.out.println("To east or west.");
break;
case 'S':
case 'N':
System.out.println("To south or north.");
break;
default:
System.out.println("We are lost.");
}
We are lost.
char character = 'A';
if (character == 'A') {
System.out.println("It's A");
} else if (direction =='B') {
System.out.println("It's B");
} else {
System.out.println("Unknown");
}
int
, byte
, short
, char
, or String
char character = 'A';
switch (character) {
case 'A':
System.out.println("It's A");
break;
case 'B':
System.out.println("It's B");
break;
default:
System.out.println("Unknown");
}
Intermediate Java