You are here:   HomeJava ProgrammingControl Structures in JavaJava If Statement | Java Example
by Dinesh Thakur Category: Control Structures

This statement helps in choosing one set of statement out of two sets depending on the validity of the logical expression included. It is also known as conditional branch statement as it is used to route program execution through two different paths.

 

Syntax:

if (logical expression)

statement(s);

else

statement(s);

If the expression in the parentheses evaluates to true, then if section is executed and if the expression evaluates to false, then else section is executed. Else section is optional.

 

/* Enter marks and print first div if marks >=60 otherwise print second division. */

import java.io.*;

class IfCondition

{

            public static void main(String[] args)

            throws IOException

            {

                        BufferedReader k=new BufferedReader(new InputStreamReader

                                    (System.in));

                        String h;

                        int m;

                        System.out.print("Enter marks : ");

                        h=k.readLine();

                        m=Integer.parseInt(h);

                        if(m>=60)

                        {

                                    System.out.println("First Division");

                        }

                        else

                        {

                                    System.out.println("Second Division");

                        }

            }

}

 

User is asked to enter a value which is stored into an integer variable m. If the value entered in m is greater then or equal to 60, control will execute if section displaying "First Division" on the screen and in case the value in variable m is less then 60, control will execute else section.