An if statement in Java is the simplest decision-making statement that allows to specify alternative paths of execution in a program. It is also called a conditional control statement or selection statement in Java.
The if statement executes a set of statements when a certain condition is true. In other words, it allows us to execute a certain block of code if certain conditions are met. It is used to change the flow of the program.
Syntax of Conditional If Statement in Java
In Java, an if statement consists of a boolean expression followed by one or more statements. The general syntax to declare the conditional if statement is as follows:
if(Condition)
statement; // statement to be executed if the condition is true.
or,
if(Condition)
{
statements; // statements to be executed if the condition is true.
}In the above syntax of if statement,
- The condition is a boolean expression that returns a boolean value, either true or false.
- The condition can also include any relational operators and logical operators to form complex boolean expressions or conditions that must be enclosed within parentheses.
- If the condition is true, the statement is executed.
- The statement is bypassed or skipped if the condition is false.
- If the block of an if statement contains more than one statement, it must enclose these statements within a pair of braces ({ }).
Flow-Chart Diagram of If Statement in Java
Look at the diagram below to understand the if statement flowchart.
Various Valid Examples of If Statement
Let’s understand the if statement with the help of various examples.
Example 1:
int myPer = 92;
if(myPer >= 80)
System.out.println("Grade A");In this example, the boolean expression (i.e., condition) evaluates to true. Therefore, the statement block will execute and print the message “Grade A” on the console. In case the boolean expression evaluates to false, the statement will not be executed.
Example 2:
if(true)
// This statement will execute because the condition is true.
System.out.println("Statement will execute."); // It will print the statement.
if(false)
// This statement will not execute because the condition is false.
System.out.println("Statement will not execute."); // It will not print statement.Example 3:
if (radius >= 0)
{
float area = radius * radius * PI;
System.out.println("Area for circle of radius " +radius + " is " + area);
}In this example, if the boolean expression evaluates to true, statements in the block will execute. That is, if the value of the radius is greater than or equal to 0, the area of circle will be computed, and the result will be displayed on the console. Otherwise, the two statements inside the block will be skipped, not executed, and continue with the program.
Valid Examples of If Statement
1. int x = 1;
if(x > 0)
System.out.println(x+ " is a positive number");
2. int x = 1;
if(x) // Same as : if(x != 0)
System.out.println(x+ " is a nonzero number");
3. int x = 10, y = 10;
if(x == y)
System.out.println("x and y are equal number");
4. int x = 5, y = 10;
if(x < y) {
System.out.println("x is less than y");
}
5. boolean x = true;
if(x) // Boolean value is used to whether the condition is true or not.
System.out.println("You are eligible for voting");Types of Selection Statements in Java
The Java language also supports several types of selection statements, which are as follows:
- One way if statements
- Two-way if-else statements
- Nested if statements
- Multi-way if-else statements
- Switch statements
- Conditional expressions
Example Program Based on If Statement in Java
Let’s take a simple example program where we will input marks for three subjects, such as maths, chemistry, and physics. Then, we will calculate the percentage of three subject marks and display “Grade A” if the percentage is greater than or equal to 85. We will use Java if statement to make a decision. We will use Java Scanner class to take inputs from the users.
Example 4:
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
// Create an object of Scanner class to take inputs for three subjects.
Scanner sc = new Scanner(System.in);
System.out.println("Enter your physics marks:");
int phyMark = sc.nextInt();
System.out.println("Enter your chemistry marks:");
int chemMark = sc.nextInt();
System.out.println("Enter your maths marks:");
int mathsMark = sc.nextInt();
float total = phyMark + chemMark + mathsMark;
float myPer = total/3;
System.out.println("Your percentage: " +myPer);
if(myPer >= 85.0) // Here, if the specified condition is true, the below statement will execute.
System.out.println("Grade A");
}
}Output:
Enter your chemistry marks: 95 Enter your maths marks: 100 Your percentage: 97.666664 Grade A
Let us take an example program to prompt the user to enter a number. If the number is divisible by 2, the program displays a message “number is divisible by 2”.
Example 5:
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
// Create a scanner object.
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer number:");
int num = sc.nextInt();
if(num % 2 == 0)
System.out.println(num +" is divisible by 2");
if(num % 2 != 0)
System.out.println(num + " is not divisible by 2");
}
}Output:
Enter an integer number: 98 98 is divisible by 2
Use of Logical Operators in If Statement
Logical operators can be used in the expression when we want to check multiple conditions together. There are three types of logical operators in Java:
- && (AND)
- || (OR)
- ! (Not)
Let’s take some example programs based on logical operators used in the if statements.
Example 6: Logical AND (&&)
public class Test {
public static void main(String[] args)
{
int x = 20, y = 40, z = 50;
if((y > x) && (y < z))
System.out.println("y is greater than x but smaller than z");
if((x < y) && (y < z))
System.out.println("z is greater than x, y");
if((x < y) && (y < z))
System.out.println("x is smaller than y, z");
}
}Output:
y is greater than x but smaller than z z is greater than x, y x is smaller than y, z
In the preceding example, if statements will produce true only if both expressions are true. If any of the expressions are false or both expressions are false, if statements will produce false.
Example 7: Logic OR (||)
public class Test {
public static void main(String[] args)
{
int x = 20, y = 10, z = 40;
boolean value;
if(value = (x > y) || (y < z))
System.out.println(value);
if(value = (x > y) || (y > z))
System.out.println(value);
if(value = (x < y) || (y < z))
System.out.println(value);
if(value = (x < y) || (y > z))
System.out.println(value);
}
}Output:
true true true
In this example program, if any of the expressions are true or both expressions are true, it will execute the true part. If both expressions are false, the statement will not execute.
Example 8: Logical Not (!)
public class Test {
public static void main(String[] args)
{
int x = 20, y = 10;
boolean value;
if(value = (x == 20) && (y != 20))
System.out.println(value);
}
}
Output:
true
We can combine several expressions by using the logical NOT operator. The result will be a boolean type.
Best Practices for Using If Statement in Java
While using the if statement in Java program, you must keep in mind some key points for the best practices:
- Maintain proper indentation and formatting for good code readability.
- Avoiding common mistakes like using assignment (=) instead of equality (==).
- Writing clear and concise conditional expressions for better code understanding.
- Do not overuse if statements, leading to complex and hard to understand code.
Scenarios to Use If Statement
You can widely use “if” statement in various scenarios, including:
- Checking user input for validity.
- Validating data before processing.
- Handling errors and exceptions gracefully.
Conclusion
In conclusion the if statement in Java is a fundamental feature for implementing decision-making statements in the program. It allows us to execute a certain block of code based on whether specified conditions are true or false.
We hope that you will have understood the basic syntax of applying an if statement and practiced all example programs. In the next, we will understand its variations like the if-else block, else-if ladder statements, and nested if statements in Java.




