In Java, control statements are used to control the flow of execution in a program. Here are some of the basic control statements in Java:
1. If-else statement: This statement is used to execute a block of code if a condition is true, and a different block of code if the condition is false. For example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
2. Switch-case statement: This statement is used to execute different blocks of code depending on the value of a variable. For example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
This will print “Tuesday” because the value of `day` is 2.
3. Loops: Loops are used to execute a block of code repeatedly. There are three types of loops in Java:
– `for` loop: This loop is used to execute a block of code a specific number of times. For example:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This will print the numbers 0 to 4.
- `while` loop: This loop is used to execute a block of code while a condition is true. For example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
This will print the numbers 0 to 4.
- `do-while` loop: This loop is similar to the `while` loop, but the block of code is executed at least once before the condition is checked. For example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
This will also print the numbers 0 to 4.
These are some of the basic control statements in Java. They are used extensively in programming to make decisions and control the flow of execution in a program.