0% found this document useful (0 votes)
4 views8 pages

Understanding Else Statement in Java

The document explains the use of the 'else' statement in programming, illustrating its function with examples in Java. It shows how the 'else' condition executes when the 'if' condition is false, providing specific outputs based on boolean and integer conditions. Key notes emphasize the absence of a condition for 'else' and the importance of syntax to avoid errors.

Uploaded by

dangebrielt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Understanding Else Statement in Java

The document explains the use of the 'else' statement in programming, illustrating its function with examples in Java. It shows how the 'else' condition executes when the 'if' condition is false, providing specific outputs based on boolean and integer conditions. Key notes emphasize the absence of a condition for 'else' and the importance of syntax to avoid errors.

Uploaded by

dangebrielt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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.

You might also like