if-else statement:

The general form is:

if(b)
{
action,b is true
}
else
{
action.b is false
}

Where b is anything or expression that should be a boolean value.

if(condition)
statement1;
else
statement2;

Here each statement may be a single statement or compound statement enclosed in a block. The condition is any expression that returns a Boolean value and else part is optional. The mechanism is if the condition is true, then statement1 is executed, otherwise statement2 will be executed. Consider an example :

class IfElseDemo
{
    public static void main(String args[ ])
    {
        int x=15;
        if(x<20)
        System.out.println("JavaRace");
        else
        System.out.println("JavaExcellence");
    }
}

Download Code
Output
JavaRace

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. A loop is defined as the repetition of instruction till the condition is satisfied.

class IfElseDemo1
{
     public static void main(String[] args)
     {
         int x=0;
         if(x)
     {
         System.out.println("Silan Software");
     }
         else
     {
         System.out.println("JavaRace");
     }
     }
}

Output

Compilation Error: incompitible types
found : int
required : boolean

class IfElseDemo2
{
     public static void main(String[]args)
     {
         int x=10;
         if(x=20)
     {
         System.out.println("Silan Software");
     }
         else
     {
         System.out.println("JavaRace");
     }
}

Output

Compilation Error

Compilation Error: incompitible types
found : int
required : boolean

let's see some other example for better clarity:

1. intx=50;
  if(x==50)
  {
   s.o.p("Hi");
  }
  else
  {
   s.o.p("Hello");
  }


Output:
Hi


2. boolean b=false;
  if(b)
  {
   s.o.p("Hi");
  }
  else
  {
   s.o.p("Hello");
  }


Output:
Hello

3. boolean b=false;
  if(b==false)
  {
   s.o.p("Hi");
  }
  else
  {
   s.o.p("Hello");
  }


Output:
Hi

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

Silansoftware Pvt.Ltd, BBSR
Call to: 0674-2361252

Comment