Java type casting example : Using type casting in java


The process of converting one data type to another is called as type casting. Type casting becomes unavoidable on many occasions. Type casting is done to take advantage of certain features of type hierarchies.

Type casting is of types,
  1. Implicit type casting
  2. Explicit type casting

The term used for implicit type casting is coercion. The most common form of explicit type casting is called as casting. Explicit type casting can also be achieved with independently defined conversion routines for example overloading object constructor.

Implicit type casting

Implicit type casting, also known as coercion is an automatic type casting by the compiler. Some languages allow, or even require, compliers to provide implicit type casting. In a mixed-type expression, the program will execute properly if the data of one or more subtype can be converted to a super type.

Example:
short num1=1000;
int num2;
num2=num1;

In the above example, the value of “a” i.e. short has been promoted to type int without using any type casting operator. This is called as standard type casting. Standard type casting affects fundamental data types. When working with floating point numbers, sometime these conversions may imply a loss of precision, where the complier will show a warning. This can be avoided with an explicit type casting.

Explicit type casting

A lot of conversions, especially those that imply a different interpretation of the value, require explicit type casting.

Example:
short num1=1000;
int num2;
num2= (int) num1; //cast notation
num2=int(a); //functional notation

Explicit conversion of several kinds like checked, unchecked or bit pattern.

No comments:

Post a Comment