Type Cast Operator
Table of Contents
There are two types of primitive type castings a possible.
- implicit type casting
- explicit type casting
Implicit Type Casting
- Compiler is responsible for this type casting.
- performed automatically where ever we are assigning smaller value to the bigger data type
- It is also known as Widening or up casting
- There is no loss of information in this typecasting
Explicit Type Casting
- Programmer is responsible for this type casting.
- It requires where ever we are assigning bigger value to the smaller data type
- It is also known as Narrowing or down casting
- 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
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.