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.
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.
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.
Liked it! Share this Tutorial