Showing posts with label implicite. Show all posts
Showing posts with label implicite. Show all posts

Wednesday, July 23, 2014

What is difference between Typecasting and Coercion in Java

In computer science, typecasting, and coercion are different ways of changing an entity of one data type into another either implicitly or explicitly. This is done to take advantage of certain features of type hierarchies or type representations.
The process by which a compiler automatically converts a value of one type into a value of another type is called as 
Coercion.
Let us see, how coercion and casting are different in following example.
Coercion (implicit):
double d = 3.0 ;
int i =1 ;
if (d > i) d = i;
Cast (explicit):
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc;
 //result == 9

integer i is getting converted into type double implicitly. Implicit conversion from int to double is possible since size of int(4 Byte) is less than the size of double(8 Byte). Whereas conversion of double to int is not an implicit conversion rather its explicit conversion since size of double is larger than size of int.
compiler does implicit conversion only when there is no precision loss, for example
int j = da // double (da=3.3) can not be converted into int implicitly since after conversion there is loss of precision by 0.3.