- Author

- Name
- Nelson Silva
- Social
Introduction
Conditional structures are fundamental in any programming language. They allow the program to make decisions based on certain criteria. In Java, the if, else if and else structures are used for this purpose.
How Do They Work?
if
The if statement evaluates a boolean expression. If the expression is true, the block of code inside the curly braces { } is executed.
if (condition) {
// Code to be executed if the condition is true
}
else if
The else if statement is an extension of the if statement. It allows you to check multiple conditions. If the if condition is false, it will check the else if condition.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
}
else
The else statement is executed when all previous conditions (from if and else if) are false.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if all previous conditions are false
}
Practical Example
Analysing an example in more detail:
package com.caffeinealgorithm.programaremjava;
public class IfElseIfAndElse {
public void Run() {
int x = 30;
if (x == 10)
System.out.println("The value of x is equal to 10.");
else if (x == 20)
System.out.println("The value of x is equal to 20.");
else
System.out.println("The value of x is different from 10 and 20.");
}
}
In this example, since x is 30, all conditions in the if and else if are false, therefore, the code inside the else block is executed.
Additional Considerations
- Priority: Java evaluates conditions in the order they appear. As soon as it finds a true condition, it executes the corresponding code and ignores the rest.
- Nesting: It is possible to nest
if,else ifandelsestatements, but care must be taken to keep the code readable and maintainable. - Logical Operators: It is possible to combine multiple conditions using logical operators such as
&&(and) and||(or).
Conclusion
Conditional structures in Java, as in many other languages, are essential for controlling the flow of execution of a program. Fully understanding if, else if and else is fundamental for any Java developer.