Control Statements
Introduction
Control statements in Java are used to control the flow of execution of a program. Normally, Java executes code line by line from top to bottom, but control statements allow us to change this flow based on conditions or repetition.
if statements
The if statement in Java is a decision-making statement used to execute a block of code only when a specified condition is true.
Example
public class Main {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote");
}
}
}
If-Else Statement
The if-else statement in Java is a decision-making statement used to execute one block of code when a condition is true, and another block when the condition is false.
Example
public class Main {
public static void main(String[] args) {
int number = 15;
if (number % 2 == 0) {
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
}
}
if-else-if ladder
The if-else-if ladder in Java is used when we need to check multiple conditions. It allows the program to choose one block of code from many options.
The conditions are checked one by one from top to bottom. As soon as a condition becomes true, its block is executed and the remaining conditions are skipped.
Example
public class Main {
public static void main(String[] args) {
int marks = 82;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}
Nested If Statement
A nested if statement in Java means placing one if statement inside another if statement. It is used when we need to check multiple conditions in a hierarchical way.
The inner if is executed only when the outer if condition is true.
Example
public class Main {
public static void main(String[] args) {
int age = 20;
int weight = 55;
if (age >= 18) {
if (weight >= 50) {
System.out.println("You are eligible");
}
}
}
}
Switch Statement
The switch statement in Java is a decision-making statement used to execute one block of code among many options based on the value of a variable.
It is an alternative to the if-else-if ladder when we need to compare a single variable with multiple values.
Example
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
default:
System.out.println("Invalid Day");
}
}
}