Thursday 5 November 2020

The Type Promotion Rules in JAVA

 

 

 

 The  Type Promotion  Rules :-


Java  defines several  type promotion  rules that  apply to expressions. They are as follows : all byte , short , and char values are promoted ti int. Then , if one operand is a long , the whole expression  is promoted to long .If  one operand is a float  , the entire expression is  promoted to float. If  any  of the operands is double. the result is double. 

           The following  program  demonstrates how each value in the expression  gets promoted to match the second argument  to each  binary operation :



Program :-

class Promote

 {

     public static void main(String args[])

     {

        byte b = 42;

        char c = 'a';

        short s = 1024;

         int i = 50000;

        float f = 5.67f;

         double d = .1234;

         double result = (f * b) +(i / c) -(d*s);

     

    System.out.println((f * b) + "+" +(i /c) +  "-" +(d *s));

  

   System.out.println("result =" +result);

 

        }

  }

 

 

OUTPUT:-

 

238.14 +515 -126.3616

result =626.7784146484375

 

 

 

The  type promotions that  occur in following  line from program :-

     double result = (f *b) + (i / c) - (d * s);


 In the first  subexpression,  f  *b , b is promoted  to a float  and the result of the subexpression  is  float. Next  , in the subexpression  i /c , c is promoted to int , and  the  result  is of type int . Then , in d* s,  the value of s  is promoted  to double, and the  type of   the subexpression  is double. 

                          

                     Finally , these  three  intermediate values, float , int , and  double are  considered.  The  outcome  of  float plus an  int is a float.  Then the  resultant float   minus the last  double is promoted  to double,  which  is the type  for  the final  result  of the expression.


 

 


No comments:

Post a Comment

Student Marks Calculation app using java

      import javax.swing. *; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; public class Student { private J...