Site icon Narayana Tutorial

Types Cast Operator

Type Cast Operator

There are two types of primitive type castings a possible.

  1. implicit type casting
  2. explicit type casting

Implicit Type Casting

  1. Compiler is responsible for this type casting.
  2. performed automatically where ever we are assigning smaller value to the bigger data type
  3. It is also known as Widening  or up casting
  4. There is no loss of information in this typecasting

Explicit Type Casting

  1. Programmer is responsible for this type casting.
  2. It requires where ever we are assigning bigger value to the smaller data type
  3. It is also known as Narrowing or down casting
  4. There may be a chance of loss of information in this typecasting.

The following is the list of all possible automatic promotions.

byte–> short–> int ( char )–> long–> float–> double–>

Ex:-1.

double d = 10 ;

s.o.p ( d) ; // 10.0

compiler automatically

Ex:-2.

int ch = 'a' ;

s.o.p ( ch ) ; 10.0

promotes from 10 to 10.0

The following conversion requires explicit type casting:-

byte <—- short <—- int ( char ) <—- float <—- double

Ex:-   byte b = 130 ; ( compile time error)

byte b = ( byte ) 130 ;

s.o.p ( b) ; // -126

Where we are assigning bigger datatype values to the smaller datatype by explicit typecasting, the most significant bits will be lost.

byte b = 130

130 = 00000------0

b = 1000010

1111101

1111111 ==> 126



int a = 150 ;

byte b = ( byte ) a ;

short s  = ( short ) a ;

s.o.p ( b ) ; // -106

s.o.p ( s ) // 150

Where we are trying to assign floating point values to the integral type by explicit type casting the digits after the decimal point will be lost.

double d = 10.235

int a = ( int ) d ;

s.o.p ( a ) ; // 10

byte b = (byte ) 130.625 ;

s.o.p ( b ) ; // -126