Conditional Statement
Learn the conditional statement in Java.
The most commonly used conditional statement in Java is the if
statement. It contains a conditional expression and a true branch, and it may contain a false branch. The true branch is executed when the conditional expression is true. The false branch, if present, is executed when the conditional expression is false. The following program demonstrates the use of the conditional statement.
Note: The true branch of the
if
statement starts the execution after the starting bracket{
and executes all the statements until the ending bracket}
.
Syntax
if (conditional expression) // no semicolon here
{
// execution starts from here if the conditional expression is true
//until here
}
else
{
//if the true branch is not executed, then this part of the code is executed
//until here
}
We want to write a program that determines eligibility for a driver’s license based on the age
input by the user. The eligible age should be or above.
import java.util.Scanner; class Test { public static void main(String args[]) { Scanner myObj = new Scanner(System.in); int age; System.out.println("Enter your age: "); age = myObj.nextInt(); // Taking age input if (age >= 18) // If age is greater than or equal to 18 { System.out.println("You are eligible for a driver's license."); } else { System.out.println("You are not eligible for a driver's license."); } } }
The conditional statement used in the program above starts with if
...