Wednesday, December 7, 2011

Conversion and Casting

Tracing technique for casting (primitive data types)
******************************

byte ---> short ---> int ---> long ---> float ---> double
char ----> int ---> long ---> float ---> double

In the above chart, if you can trace path from one element to another element, then that cast is safe (or) implicit cast happens.
For ex: conversion of byte to float is fine as you can trace the path. Reverse (float to byte) is not safe as you cannot trace the path.

****************************************************
Primitive Data Type - Conversion (Implicit Casting)
****************************************************

For primitive data types, this happens in the following cases

1. Assignment operations
int i;
double d;
i=10;
d=i; // Implicit Casting happens here

2. Method call

int i=10;
foo(i); // Implicit Casting happens here

public void foo(long l) {
...
}

3. Arithment promotions
int i =10;
long l = 20;
long result = l/i; // Implicit Casting happens here as part of arithmetic promotions.

****************************************************
Primitive Data Type - Explicit Casting
****************************************************
int i;
long l;
l = (long) i; // Works - even though this is not necessary. Implicit cast happens if we don't specify it.
i = (int) l; // Explicit casting. Narrow down cast always needs Explicit casting. This compiles and works. But result could be unexpected as most significant bits will be lost.


****************************************************
Object References - Conversion (Implicit Casting)
****************************************************
TBD.

****************************************************
Object References - Conversion (Explicit Casting)
****************************************************
TBD.

Reference:
Java Certification Book.

No comments: