Java Control Statements Page
Syntax
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
while (condition) {
// code to be executed while condition is true
}
for (int i = 0; i < count; i++) {
// code to be executed for each iteration of the loop
}
switch (variable) {
case value1:
// code to be executed if variable equals value1
break;
case value2:
// code to be executed if variable equals value2
break;
default:
// code to be executed if variable does not match any case
}
Example
Use if statement to check if a number is positive, negative or zero.
int num = -10;
if (num > 0) {
System.out.println("Positive Number");
} else if (num < 0) {
System.out.println("Negative Number");
} else {
System.out.println("Zero");
}
Output
Negative Number
Explanation
Java control statements are used to control the flow of execution of a program. There are different types of control statements like if statement, while loop, for loop, switch statement.
The if statement is used to test a condition and execute a block of code if the condition is true. The else statement can be added to execute a block of code if the condition is false.
The while loop is used to execute a block of code repeatedly while a condition is true.
The for loop is used to execute a block of code for a specified number of iterations.
The switch statement is used to select one of many blocks of code to be executed based on the value of a variable.
Use
Control statements are used to control the flow of execution of a program. They are used to make decisions based on certain conditions, execute code multiple times, iterate over a collection of elements and select one out of many options.
Important Points
- Control statements are essential for programming in Java.
- Use them to control the flow of execution of a program.
- Different types of control statements include if statement, while loop, for loop, and switch statement.
- Take care not to introduce infinite loops when using control statements.
Summary
Java control statements are used to control the flow of execution of a program. They are essential for making decisions, iterating over a collection of elements and selecting one out of many options. Different types of control statements include if statement, while loop, for loop, and switch statement. They are powerful tools for building complex software programs.