/    /  Type Casting

Type Casting

 

Generally the data type conversions or the type casting can be possible in the following three ways.

  1. Automatic Conversion using assignment operator.
  2. Conversion to higher type in expressions (implicit)
  3. Using cast operator (Explicit)

 

Automatic Conversion using assignment operator:

 

If we are using the assignment operator the right side value can be automatically converted into left side.

 

Example1:

 

int x=5;
float y;
y=x;

 

Example2:

 

int x;
float y=3.5;
x=y;

 

Conversion to higher type in expressions (implicit):

 

If we are using an arithmetic expression that contains different types of data then the resultant value type is equal to the higher type data of the expression. Automatically converts lower type to higher type before the operation performed by the compiler and ultimately the result in the form of higher type is known as implicit conversion.

 

Example:

 

int a; 
float b;
double c, x; 
x=a*b+c;

 

Using cast operator (Explicit):

 

We can also perform type conversion explicitly by using a cast operator in the following way.

 

Syntax:

 

(Type name) expression; or (Type name) variable;

 

where type name is any of c data types and expression may be a constant, variables or any arithmetic expressions.

 

Ex-1:

 

a= (int) 8.65;  
It returns a=8

 

Ex-2:

 

x= (float) 7;
It returns x=7.000000

 

Ex-3:

 

y= (int) 6.5/ (int) 2.3;
y=int (6/2);
It returns y=3