If-else statement in Java

If-else statement in Java

If else statement comes under selection looping structure. When a programmer wants compiler to select one of the two alternatives available, programmer can use if else structure. We can also use if statement without else statement. If else structure reduces the length of the code. It is an alternative to switch case. Let’s see an example of if else statement in Java. Syntax-

if (condition)

Q. Write a program to check the equality of 2 numbers in Java

import java.util.Scanner;
class rough
  public static void main(String[] args) {
    int a, b;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter 2 numbers: ");
    a = sc.nextInt();
    b = sc.nextInt();
    if (a == b)
    else if (a > b)
      System.out.println("First number is greater");
      System.out.println("Second number is greater");


if else java output


First, two variables are declared with integer data type. The compiler then asks user to enter two numbers. After that, if condition is checked. If the first condition a==b is true then “Equal” is printed. Else the next condition is checked. If a>b is true then “First number is greater” is printed. If it is false then the else part, “Second number is greater” is printed.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. Scanner– Scanner is a class in java. util package used for obtaining the input.
  7. String[] args– Used for command line argument.
  8. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.
  9. System.in is an InputStream.


So this is the concept of if else statement in Java. We hope it was clear to you. If you have any doubts tell us in the comment section. For daily updates and more such content do follow us on Instagram.

Keep programming!



Leave a Reply

Your email address will not be published. Required fields are marked *