Type Coversion in Java


☞When different types of variables and constants are mixed up in an expression, they are converted in one common type implicitly by the compiler. This is called type conversion.

☞Type conversion are in two forms:

1.implicit type conversion
2.explicit type conversion

Implicit Type Conversion

☞An implicit type conversion is a conversion performed by the compiler without programmer’s intervention.

☞It is also known as type promotion or Coercion.

Example

class Implicit{
public static void main(String args[]){

int a=10;  
float f=a;     //type promotion						
System.out.println(a);  
System.out.println(f);

}
}

Output

10
10.0

Explicit Type Conversion

☞An explicit type conversion is user-defined that forces an expression to be of specific data type.

☞It is also known as type casting.

Example

class Explicit{
public static void main(String args[]){

float f=10.5f;
int a=(int)f; //int a=f;(compile time error)                              
System.out.println(f);  
System.out.println(a);  

}
}

Output

10.5
10
Note : If you will do typecast then it means you are doing forcefully as you can see int a=(int)f; here data is lost but no error.

Permitted Conversion

byte to short, int, long, float or double

short to int, long, float or double

char to int, long, float or double

int to long, float or double

long to float or double

float to double