ELSE
STATEMENT
Think of it like real life: If it rains, bring an umbrella. Otherwise (else), go outside without one:
Example
boolean isRaining = false;
if (isRaining) {
[Link]("Bring an umbrella!");
} else {
[Link]("No rain today, no need for an umbrella!");
}
Example:
public class Main {
public static void main(String[] args) {
boolean isRaining = false;
if (isRaining) {
[Link]("Bring an umbrella!");
} else {
[Link]("No rain today, no need for an umbrella!");
}
}
}
Output:
No rain today, no need for an umbrella!
Example:
public class Main {
public static void main(String[] args) {
boolean isRaining = false;
if (isRaining) {
[Link]("Bring an umbrella!");
} else {
[Link]("No rain today, no need for an umbrella!");
}
}
}
Output:
No rain today, no need for an umbrella!
Another Example:
int time = 20;
if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good
evening.");
}
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
[Link]("Good day.");
} else {
[Link]("Good evening.");
}
}
}
Output:
Good evening.
Example explained:
In the example above, time (20) is greater than 18, so
the condition is false. Because of this, we move on to
the else condition and print to the screen "Good
evening". If the time was less than 18, the program
would print "Good day".
Notes:
else does not have a condition - it runs when the if
condition is false.
Do not put a semicolon right after if (condition).
That would end the statement early and make else
behave unexpectedly.