Java Control Statement
In java, control statements are used to control the flow of the program execution. These statements are used to make decisions, loops, and to perform branching based on certain conditions.
Here are some examples of control statements in Java:
- If statement: The if statement is used to execute a block of code if a certain condition is true.
Example:
goint num = 10;
if (num > 5) {
System.out.println("num is greater than 5");
}
- If-else statement: The if-else statement is used to execute a block of code if a certain condition is true and another block of code if the condition is false.
Example:
goint num = 10;
if (num > 5) {
System.out.println("num is greater than 5");
} else {
System.out.println("num is less than or equal to 5");
}
- Switch statement: The switch statement is used to select one of many code blocks to be executed.
Example:
goint 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");
}
- While loop: The while loop is used to execute a block of code repeatedly as long as a certain condition is true.
Example:
cssint i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
- For loop: The for loop is used to execute a block of code repeatedly for a fixed number of times.
Example:
cssfor (int i = 0; i < 5; i++) {
System.out.println(i);
}
Comments
Post a Comment