Automatic Type Promotion



Java perform arithmetic operations on equal data type. For example in a expression their are two operands of integer and float type then java automatically promote int to float. This is also known as automatic type promotion.


Remember ! Java won't allow arithmetic operations on byte, short, char data type. If there is any variable from these data types then those variable automatically promoted to integer data type variable. Then operation will be performed.

Example :

	//file: promote.java
	// www.jgyan.com
class promote
 {
 public static void main(String arg[])
  {
   int a=12;
   float f=4.3f;
   double d=34.4;
   
   d= a * f + d;
   System.out.println("d:"+d);
  }
 }
/*Output:
d:86.0000022888183
*/

In above program int promoted to float and then to double.


 = int * float + double ;
= float * float + double ;
= float + double ;
= double + double ;
= double ;

To perform any arithmetic operation, both operands must match their data type, if not then compiler promote lower data type to upper data type.

byte, short, char promotion to int

Before discussing this topic, just have a look on the program given below.

 //file:promote.java
 //www.jgyan.com
class promote
 {
 public static void main(String arg[])
  {
   byte b=12;
   b=b+1; // Error
   System.out.println(b);
  }
 }


You might be surprised code looks okay, then why it's not compiling. Reason is the automatic type promotion of byte data type to integer. In statement "b=b+1" variable b in expression (right side of '=' operator) is promoted to integer.

 = byte + int ;
= int + int ;
= int ;

Result of expression b+1 is integer, but we are storing result in byte variable without performing any type casting.

//file: promote1.java
// www.jgyan.com
  class promote1
 {
 public static void main(String arg[])
  {
   byte b=12;
   b=(byte)(b+1); 
   System.out.prinltn(b);
  }
 }



Now if we will write same program using "++" pre or post increment operator. then there won't be any error, Why?

 //file: promote2.java
// www.jgyan.com
class promote2
 {
 public static void main(String arg[])
  {
   byte b=12;
   // b++ expanded into b=(byte)(b+1);
   b++; 
   System.out.prinltn(b);
  }
 }
/* Output:
13
*/

Actually pre and post increment/decrement operator has type casting implicit in their definition.


 b++; 
 //equal to  b = (byte)(b+1);