Data Type Conversion in Java

Introduction 

 
Typecasting is a technique in which we convert one type of value into another type of value. There are two types of typecasting.
1. Narrowing
2. Widening

Narrowing: 

 
Narrowing typecasting is also known as explicitly typecasting. In this type of casting there is a chance of data loss. Then java produces an error message “Possible loss of precession.”
To remove this error we must explicitly typecast.
 
Example:
  1. class Narrowing {  
  2.  public static void main(String… args) {  
  3.   int I;  
  4.   double d = 1.0;  
  5.   i = (int) d;  
  6.   System.out.print(i);  
  7.  }  
  8. }   

Widening:

 
When the lower data type is assigned to a higher data type then there is no chance of data loss. So this type of conversion is automatically done by java. 
  1. class Widening {  
  2.  public static void main(String… args) {  
  3.   int I = 5;  
  4.   double d;  
  5.   d = i;  
  6.   System.out.print(d);  
  7.  }  
  8. }