print
Advertisment
Advertisment

conditional operator

The conditional operator is also known as the ternary operator.This operator has one condition and two expression and is used to evaluate Boolean expressions.This operator is used. Checking the condition then it will give boolean value according to the condition if condition is true then it will execute expression 1else if condition is false. So it will execute expression 2.

  • The condition operator acts like an if esle.but if else conditional statement is mostly uses.
  • Ternary operator takes less time and less code as compared to if else.

Syntax

condition?Expression1:Expression2

Example 1


   class Ternary{
      public static void main(String[] args) {
         int a = 10;
         int b;
         b = (a==1)?(40):(60); //condition is false then 60 will assign to b
         System.out.println(b);         
         b = (a==10)?(50):(100); //condition is true then 50 will assign to b
         System.out.println(b);
      }
   }

Output :

 
   
      60
      50
   

Advertisment

Example 2


   import java.util.Scanner;
   class Ternary{
      public static void main(String[] args) {
         Scanner scr = new Scanner(System.in);
         System.out.println("Enter username");
         String username = scr.nextLine();
         System.out.println("Enter passward");
         String passward = scr.nextLine();
         System.out.println((username=="user" && passward=="password@123")?"login succesfully":"username & passward is wrong");
      }
   }

Output :

 
   
     Enter username
     user
     Enter password
     password@123
     login succesfully
   
Advertisment
Advertisment
arrow_upward