If-else Statement in Java

  • Facebook
  • Google
  • LinkedIn
  • Twitter

If-else condition in Java is a conditional branch statement, which is used to test the condition.

if the a condition is true then it executes the statement1, if the condition is false then it executes statement2.

Here is the syntax of an if-else statement.

    if(condition)
    {
        statement1;
    }
    else
    {
        statement2;
    }

Example of If-else.

package com.javatutsworld.test;

class MainApp {
	public static void main(String arg[]) {
		int marks = 65;
		if (marks > 60) // line x
		{
			System.out.println("You got good markes"); // line y
		} else {
			System.out.println("Sorry you did not get good markes"); // line z
		}

	}
}

Output:

You got good markes

In this program variable marks are initialized to 65 and checked the condition in the line x if marks > 60 is true then line y is executed which prints You got good markes.

If-else if-else Statement

if-else-if statement check condition from top to bottom and executes one condition from multiple statements.

Here is the syntax of an if-else statement


    if(condition1)
    {
        statement1;
    }
    else if(condition2)
    {
        statement2;
    }
	else if(condition3)
    {
        statement3;
    }
	else
	{
 		statement4;
	}

Example of If-else if-else

package com.javatutsworld.test;

public class MainApp {
	public static void main(String[] args) {
		int marks = 65;

		if (marks < 33) { //line a
			System.out.println("Your are failed"); //line b
		} else if (marks ≥ 33 && marks < 45) { //line c
			System.out.println("You have third division"); //line d
		} else if (marks ≥ 60 && marks < 70) { //line e
			System.out.println("You have first division"); //line f
		} else if (marks ≥ 70) { //line g
			System.out.println("You have A grade"); //line h
		} else { //line i
			System.out.println("You have not given correct input"); //line j
		}
	}
}

Output


You have first division

In this program variable marks are initialized to 65 and checked the condition from top to bottom and line e condition is true so line f is executed which prints You have first division

      Advertisements