Java Programming

If else statement in Java ( Easy Learn )

In our previous article, we have discussed the testing the single condition using a simple if statement. But sometimes we need to test a condition in such a way that if the condition satisfies then one statement will be executed otherwise next statement will get executed.

In this article, we will try to explain such type of condition testing but before that, I will recommend you to go through my previous article If Statement in Java ( Learn in 2 mins ) so that your concept become more clear.

IF else statement in Java

If else statement is the type of condition testing statement which is used to test a simple condition and if the condition satisfies then the true block will be executed otherwise a false block will be executed.

True & False block are categorized using the if and else statements i.e. if statement will hold the true block whereas else statement will hold the false block.

Java if else statement

Syntax ( If…else statement )

if(condition)
{
  trueblock statement;
}
else
{
  falseblock statement;
}

The syntax of the if…else statement is simple. Let’s understand it in 4 parts:

  1. if(condition) – This is the first line of the if…else statement, it is used to test any certain condition.
  2. Trueblock statement – If the condition of if statement becomes true then this statement will be executed.
  3. Else – Suppose the condition of if statement does not satisfy, then else statement is used to execute another statement.
  4. Falseblock statement – This is another block of statement. It is executed when the condition of if block doesn’t satisfy.

Examples of if else statement

1. Test the condition that the child is boy or girl

class test
{
 public static void main(String args[])
 {
   int code=1;
   if(code==0)
   {
    system.out.print("BOY");
   }
   else
   {
    system.out.print("GIRL");
   }
  }
}

2. Program in Java to test the eligibility for voting (Example)

class test
{
 public static void main(String args[])
 {
  int age=20;
  if(age<=18)
  {
   system.out.println("Eligible to vote");
  }
  else
  {
   system.out.println("Not Eligible");
  }
 }
}

3. Program to test the result (Example)

class test
{
 public static void main(String args[])
 {
  int marks=43;  
  if(marks<=25)
  {
   system.out.println("PASS");
  }
  else  
  {
   system.out.println("FAIL");
  }
 }
}

 

Recommended 

-> Type Conversion In Java (Super Easy)

-> Decision Making & Branching Statements In Java

-> Structure of Java Program

-> Data Types in Java ( int, float, char )

-> Tokens in Java (Keywords, Identifiers, Literals)

Leave a Reply