Method Overloading (Cont.): Type Promotion


Type Promotion
One type is promoted to another implicitly if no matching datatype is found. For example, byte can be promoted to short, int, long, float, or double. The short datatype can be promoted to int, long, float, or double. The char datatype can be promoted to int, long, float, or double, and so on.

Priority wise, compiler takes the following two steps:
  1. Type conversion to a higher type (in terms of range) in the same family.
  2. Type conversion to the next higher family (e.g., assume there is no long data type available for an int data type, then it will search for float data type).
TypePromotion.java (type promotion)

 class TypePromotion { 
   public static void main( String[ ] args ) { 
     Demo obj = new Demo( );
     if      ( args[0].equals( "byte"   ) )
       obj.show( Byte.parseByte( args[1] ) );
     else if ( args[0].equals( "String" ) )
       obj.show( args[1] );
     else if ( args[0].equals( "int"    ) )
       obj.show( Integer.parseInt( args[1] ) );
     else if ( args[0].equals( "char"   ) )
       obj.show( args[1].(0) );
   }
 }
 class Demo {
   public void show( int x    ) { System.out.println( "int "    + x ); }
   public void show( String s ) { System.out.println( "String " + s ); }
   public void show( byte b   ) { System.out.println( "byte "   + b ); }
 }
shell> java TypePromotion            




      “We live in an age when unnecessary things are our only necessities.”    
      ― Oscar Wilde