JAVA CONDITIONS
Java else statement
else lets you run an alternative code block when the preceding if statement's condition is false.
When does the else block run?
if and else provide two possible paths. If the condition returns true, the first block runs. If it returns false, the first block is skipped and the else block runs. Only one of these blocks runs each time the condition is checked.
else statement syntax
if (sąlyga) {
// Runs when the condition is true
} else {
// Runs when the condition is false
}ifparentheses contain the condition Java checks.- If the condition is
true, the first block inside braces runs. - If the condition is
false, the first block is skipped and theelseblock. - Java selects only one of these two paths each time it checks the condition.
This syntax template produces no console output.
The word sąlyga and the comments simply show where to put the actual condition and statements to execute.
else has no condition of its own.It runs automatically when the associated if condition is false.
An everyday decision example
The program decides whether Jonas needs to take an umbrella:
boolean jonuiReikiaSkecio = false;
if (jonuiReikiaSkecio) {
System.out.println("Jonai, pasiimk skėtį!");
} else {
System.out.println("Jonai, šiandien skėčio nereikia!");
}Console output
Jonai, šiandien skėčio nereikia!
- The variable
jonuiReikiaSkeciois like a box that can hold only the answer “yes” or “no”. - Meaning
falsehere means “no, Jonas does not need an umbrella”. ifchecks this value. Since it is nottrue, the first block is skipped.- Java moves to the
elseblock and displays in the console that Jonas does not need an umbrella.
What would change with true?
Java would run the first block and display Jonai, pasiimk skėtį!. else block would then be skipped.
Important else rules
elsecomes immediately after the associatedifblock.elsecannot be used alone without a precedingif.- Each
ifcan have only one finalelseblock. - To check another condition, use an
else ifstatement.