Today, let’s dive into conditional structures in Java, like IF / ELSE. These are used to define different execution paths based on boolean conditions. To make it practical, we’ll explore an example of a system that evaluates a student’s final grade and determines whether they are APPROVED
or FAILED
. Oh, I’ll only show code snippets here without the complete class, so take this opportunity to practice creating classes (organized into packages) and main methods to run the examples. If you’re unsure, refer to previous lessons.
Example 1: Simple approval or failure
double finalGrade = 7.5;
String result = "UNDEFINED";
if (finalGrade >= 7) {
result = "APPROVED";
} else {
result = "FAILED";
}
In this example, the program checks if the grade is greater than or equal to 7.0. If true, it outputs "APPROVED"; otherwise, "FAILED."
Example 2: Adding an intermediate condition
What if we want to include a third scenario, like the possibility of an extra exam for students with grades between 6.0 and 6.9? We can use else if:
double finalGrade = 6.0;
String result = "UNDEFINED";
if (finalGrade >= 7) {
result = "APPROVED";
} else if (finalGrade >= 6.0) {
result = "EXTRA EXAM REQUIRED";
} else {
result = "FAILED";
}
Here, the program identifies three scenarios: approved students, those who need to take an extra exam, and those who fail. This type of structure is beneficial for systems requiring decisions based on multiple conditions.
Conclusion
Practicing conditional structures is essential for anyone learning Java. They form the foundation of many logic-based solutions in everyday development. So, roll up your sleeves and explore various scenarios with if
, else if
, and else
! Happy coding!
Top comments (0)