Conditionals
if, else if, and else work as
in most C-family languages, condition in parentheses, block in curly
braces.
Example: a time-of-day greeting
public class Main {
public static void main(String[] args) {
int hour = 14;
String greeting;
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
System.out.println(greeting);
}
}
Good afternoon
Notice greeting is declared without a value first, then
assigned inside whichever branch actually runs — Java requires it be
assigned exactly once along every possible path before it's used, or the
compiler refuses to build the program, another example of Java catching
a potential mistake before the code ever runs.
public class Main {
public static void main(String[] args) {
int hour = 14;
String greeting;
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
System.out.println(greeting);
}
}
Good afternoon