Casting (Type Conversion)

It is sometimes necessary to convert a data item of one type to another type.

Casting (Type Conversion)

Casting (Type Conversion)

     

It is sometimes necessary to convert a data item of one type to another type. Conversion of data from one type to another type is known as type casting. In java one object reference can be type cast into another object reference. This casting may be of its own type or to one of its subclass or superclasss types or interfaces. Some compile time or runtime type casting rules are there in java. Some circumstances requires automatic type conversion, while in other cases it must be "forced" manually (explicitly). 

Automatic Conversion

Java performs automatic type conversion when the type of the expression on the right hand side of an assignment operator safely promotes to the type of the variable on the left hand side of the assignment operator. Thus we can safely assign: byte -> short -> int -> long -> float -> double. Symbol (->) used here interprets to "to a".

Lets take an example, 

// 64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
myLongInteger = myInteger;
In the above example, extra storage associated with the long integer, simply results in padding with extra zeros.

Any object can reference to a reference variable of the type Object, as Object class comes at the top in the hierarchy of every Java class.

Java follows two types of casting
  • Upcasting
  •  Downcasting

Upcasting

Casting a reference with the class hierarchy in a direction from the sub classes towards the root then this type of casting is termed as upcasting. Upcasting does not require a cast operator.

DownCasting

On the other hand, casting a reference with hierarchal class order in a direction from the root class towards the children or subclasses, then it is known as downcasting.

Explicit Conversion (Casting)

Automatic type casting does work in case of narrowing i.e. when a data type requiring more storage is converted into a data type that requires less storage. E.g. conversion of a long to an int does not perform because the first requires more storage than the second and consequently information may be lost. In such situations an explicit conversion is required.