If Statement in Java: Syntax, Example

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, if statement consists of a boolean expression followed by one or more statements. The general syntax to declare 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,

(a) Condition is a boolean expression that returns a boolean value either true or false.

(b) Condition can also include any relational operators and logical operators to form complex boolean expressions or conditions that must be enclosed within parentheses.

(c) If the condition is true, then the statement is executed. If the condition is false, then the statement is bypassed or skipped.

(d) If the block of if statement contains more than one statement, must enclose these statements within a pair of braces ({ }).

Look at the below figure, where you can see the if conditional flowchart diagram.

Java if statement flowchart diagram

Various Valid Examples of If Statement


Let’s understand if statement with the help of various examples. Consider the following program code given below.

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, if the boolean expression evaluates to false, then the statement will not be executed.

Let’s take another very simple example code.

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.

Similarly, consider the following program code.

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 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.

Some Valid if statements are as follows:

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


Java language also supports several types of selection statements, that 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


1. 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.


Look at the program code to understand better.

Example 1:

package javaProgram;
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

2. Let’s 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”. Look at the source code to understand better.

Example 2:

package javaProgram;
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 3: Logical AND (&&)

package javaProgram;
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 program, 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 4: Logic OR (||)

package javaProgram;
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 the above example program, if any of the expressions are true or both expressions are true, then it will execute the true part. If both expressions are false, then the statement will not execute.

Example 5: Logical Not (!)

package javaProgram;
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 “Logical Not” operators. 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 well 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 statement, 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.

In conclusion, the if statement in Java is a fundamental feature for implementing decision-making statement 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 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.