whenever you're comparing one variable against a long list of values, such as
if (weather.equals("sunny")) {
// code
} else if (weather.equals("cloudy")) {
// code
} else if (weather.equals("rainy")) {
// code
} else {
// code
}
you should avoid having a long list of else if
statements, because this looks so disgusting !
Instead, you should favor using a switch
statement which was designed to compare one variable against a list of cases.
switch (weather) {
case "sunny": // code break;
case "cloudy": // code break;
case "rainy": // code break;
default: // code
}
Then you might be asking that when to use if
vs switch
?
The only thing you can really do with switch
is compare one variable against a list of values.
if
statement is more flexible so that suitable for complex conditions, such as when you need to compare multiple variables, they give you the flexibility to evaluate compound conditions using logical operators.
if (temperature >= 80 && humidity >= 60) {
System.out.println("It's too hot and humid\n");
} else {
System.out.println("It's comfortable\n");
}
See you in workbook 3.6 and 3.7