Data Type Conversion in Java

Type casting is a technique in which we convert one type of value into another type of value. There are two types of type casting.

1. Narrowing
2. Widening

Narrowing: 

Narrowing type casting is also known as explicitly type casting. In this type of casting there is chance of data loss. Then java produces an error message “Possible loss of precession.”

To remove this error we must explicitly type cast.

Example:
  1. class Narrowing  
  2. {  
  3.          public static void main (String …args)  
  4.          {  
  5.     int I;  
  6.     double d=1.0;  
  7.     i=(int)d;  
  8.     System.out.print(i);  
  9.            }  
  10.  

Widening:

When lower data type is assigned to a higher data type then there is no any chance of data loss. So this type of conversion is automatically done by java. 

  1. class Widening    
  2. {    
  3.          public static void main (String …args)    
  4.          {    
  5.     int I =5;    
  6.     double d;    
  7.     d=i;    
  8.     System.out.print(d);    
  9.            }    
  10. }
Ebook Download
View all
Learn
View all