Monday, 8 July 2019

Conditional Statements


There are four conditional statements in Java

  • if
  • if---else
  • Nested if...else
  • Switch...case


If condition 

Example:

package LearnJava;

public class JavaBasics {
      

       public static void main(String args[])
       {
             
              int a = 1;
              int b =1;
             
              if(a==b)
              {
                     System.out.println("a and b are equal");
              }
             
       }
        
}

If - -else condition

Example:

package LearnJava;

public class JavaBasics {
      

       public static void main(String args[])
       {
             
        int a=30;
        int b=40;
      
        if (a>b) {
            System.out.println("a is greater than b");
        }
        else{
            System.out.println("b is greater than a");
        }
      
        //comparison operators:
        // < > <= >= == !=
      
        int c=20;
        int d=20;
        if(c==d) {
            System.out.println("a and b are equal");
        }else {
            System.out.println("a and b are not equal");
        }
             
       }
        
}


Nested if- -else condition 

Example:

package LearnJava;

public class JavaBasics {
      

       public static void main(String args[])
       {
             
       //write a logic to find out highest number
      
        int x=700;
        int y=900;
        int z=800;
      
        //nested if-else condition
      
        if(x>y & x>z) 

        {
            System.out.println("x is the highest");
        }
        else if(y>z)
        {
            System.out.println("y is the highest");
        }
        else 

        {
            System.out.println("z is the highest");
        }
                          
       }
        
}


Switch case condition

Example:

package LearnJava;

public class JavaBasics {
      

       public static void main(String args[])
       {
             
       int number =1;
      
       switch(number+1)
       {
       case 1 :
              System.out.println("Value of number is one");
       case 2 :
              System.out.println("Value of number is two");
       case 3 :
              System.out.println("Value of number is three");
       }
       default:
              System.out.println("not available");   
       }
        
}

No comments:

Post a Comment