Java Control Statements
Java supports control statements that are used to control flow of the program's execution based on conditions. Here, in this section we will discuss about the most commonly used control statements:
- if
- if-else
- Nested if
- if-else-if
1. Java If Statement
Java if statement is a conditional statement which tests a boolean expression and executes only if the condition is true. below is the syntax to declare if statement.
if(<conditional expressional>)
<statement>
Java If Example
public class Demo {
public static void main(String[] args) {
int a = 20;
if (a>10) {
System.out.println("value is greater than 10");
}
if (a<10) {
System.out.println("value is less than 10");
}
}
}
Output:
value is greater than 10
Explaination
In the above example, we used two if statements, but only first one executes because its conditional expression returns true. As we said, if executes only when its condition is true.
2. Java If-Else Statement
Java if statement supports else statement alongside if which is optional. Else is a block which can be used to execute the statements when the if condition is false. Below is the syntax to declare if-else statement.
if(<conditional expressional>)
<statement>
else
<statement>
Java If-Else Example
public class Demo {
public static void main(String[] args) {
int a = 5;
if (a>10) {
System.out.println("value is greater than 10");
}
else {
System.out.println("value is less than 10");
}
}
}
Output:
value is less than 10
3. Java Nested If Statement
We can put if statement inside another if to create nested if. Below is the syntax to declare nested if statement.
if(<conditional expressional>){
<statement>
if(<conditional expressional>){
<statement>
}
}
Java Nested If Example
public class Demo {
public static void main(String[] args) {
int a = 20;
if (a>10) {
if (a>15) {
System.out.println("value is greater than 10 and 15");
}
}
else {
System.out.println("value is less than 10");
}
}
}
Output:
value is greater than 10 and 15
4. Java If-Else-If Statement
Java allows to put conditional expression with else to create more conditional flow. It is used to execute one condition from multiple conditions. See the below syntax.
if(<conditional expressional>){
<statement>
}
else if(<conditional expressional>){
<statement>
}
else if(<conditional expressional>){
<statement>
}
...
else{
<statement>
}
Java If-Else-If Example
public class Demo {
public static void main(String[] args) {
int marks = 70;
if (marks>80) {
System.out.println("First class");
}
else if (marks>60) {
System.out.println("Second class");
}
else if (marks>50) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
}
Explaination
Notice: We have multiple conditions here, but once a condition is satisfied all other conditions are not evaluated.