wellnwill Marathahalli Bangalore

Conditional Operator

  • It works on 3 operands and known as ternary operator.
  • Syntax- < expression 1 >? < expression 2> : < expression 3>
  • Expression 1 is boolean condition i.e. true/false.
  • If expression 1 is true then expression 2 will be executed.
  • If expression 1 is false then expression 3 will be executed.
  • We can perform listing of conditional operator.
class Test65
{
  public static void main(String args[])
  {
    boolean b=true?true:false;
    System.out.println(b);
  }
}

// O/P - true
class Test66
{
  public static void main(String args[])
  {
    byte b=true?1:2;
    System.out.println(b);
  }
}

// O/P - 1
class Test67
{
  public static void main(String args[])
  {
    byte b=10>20?1:2;
    System.out.println(b);
  }
}

// O/P - 2
class Test68
{
  public static void main(String args[])
  {
    byte b=(byte)((10>20)?1.1:2.2);
    System.out.println(b);
  }
}

// O/P - 2
class Test68
{
  public static void main(String args[])
  {
    byte b=10>20?1.1:2.2;
    System.out.println(b);
   }
}

// O/P - CompileTimeError 
       - incompatible type, possible lossy of conversion from double to byte.
       
        
class Test69
{
  public static void main(String args[])
  {
    byte b1=30;
    byte b2=40;
    int max=b1 > b2 ? 30:40;
    int min=b1 < b2 ? 30:40;
    System.out.println("max:"+max);
    System.out.println("min:"+min);
 }
}

// O/P -  max:40,min:30
Footer with Map