IF Statement in Java


The if statement is Java's conditional branch statement. It can be used to route program execution through two different paths. The if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets.

  Syntax:
     if( condition )
     {
        // body of the statements;
     }

This is a Java program that asks the user to input their age and then checks if they are eligible to vote. If the age is 18 or above, the program prints a message saying "You are Eligible For Vote...".

Here's how the program works:

  • First, it declares an integer variable called age.
  • Then, it prints the message "Enter Your Age : " using the System.out.println() method.
  • It creates a Scanner object called in to read the input from the user.
  • It reads the user's input using the in.nextInt() method and stores it in the age variable.
  • The program then checks if the age variable is greater than or equal to 18 using the if statement.
  • If the condition is true, the program prints the message "You are Eligible For Vote..." using the System.out.println() method.
  • If the condition is false, the program does nothing and exits.

Overall, this program is a simple example of how to use an if statement in Java to make a decision based on user input.

Source Code

import java.util.Scanner;
 
public class if_statement {
    public static void main(String args[]) {
        int age;
        System.out.println("Enter Your Age : ");
        Scanner in = new Scanner(System.in);
        age=in.nextInt();
        if(age>=18)
        {
            System.out.println("You are Eligible For Vote...");
        }
    }
}
 

Output

Enter Your Age :
23
You are Eligible For Vote...
To download raw file Click Here

Basic Programs