Java Numeric Promotion in Conditional Expression

JavaObject Oriented ProgrammingProgramming

The conditional operator (? :) leverages the output of one value (which is a bool) to decide which expression has to be evaluated next. Let us see an example −

Example

 Live Demo

import java.io.*;
public class Demo{
   public static void main (String[] args){
      Object my_obj = true ? new Integer(91) : new Float(89);
      System.out.println(my_obj);
   }
}

Output

91.0

A class named Demo contains the main function. Here, an object instance is defined and if it is true, an integer value is displayed otherwise a float value is displayed. Next, they are printed on the console.

When promotional expression is not written inside the conditional statement −

Example

 Live Demo

import java.io.*;
public class Demo{
   public static void main (String[] args){
      Object obj_2;
      if (true)
         obj_2 = new Integer(91);
      else
         obj_2 = new Float(89);
      System.out.println(obj_2);
   }
}

Output

91

A class named Demo contains the main function. Here, an object instance is defined and if it is true, an integer value is assigned to this object. Otherwise, a float value is assigned to this object and then the object is displayed on the console.

raja
Published on 04-Jul-2020 09:19:31

Advertisements