Java if-else statement examples
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the if-else construct is used to check if a condition is met then do something, otherwise do something else. The structure looks like follows:
if (condition) {
// do something if condition is met
} else {
// do something else if condition is not met
}where condition can be a variable, a method call or an expression that must be evaluated to true. The code inside if block can be any Java statements. For example:
boolean passed = false;
// try something...
if (passed) {
System.out.println("Congratulations!");
} else {
System.out.println("Try again next time!");
}The construct can be extended for multiple if-else pairs:
if (condition1) {
// do something if condition1 is met
} else if (condition2) {
// do something if condition2 is met
} else if (condition3) {
// do something if condition3 is met
} else {
// do something else if none condition is met
}For example:
int score = calculateScore();
if (score > 90) {
System.out.println("Excellent");
} else if (score > 70) {
System.out.println("Very good");
} else if (score > 50) {
System.out.println("Above average");
} else {
System.out.println("Very bad");
}If there is only one statement after the if or else, the opening and closing curly braces can be removed. For example:
if (score < 10)
score = score + 10;
else
score = score - 10;See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments