Casting in java

Page 1

Casting in JAVA 1) Introduction Casting in java is used when assigning a value of type TypeA to a variable of type TypeB. If you don’t know how to use java variables, please check our corresponding java variables tutorial. There are two types of casting in java: 

Implicit casting

 Explicit casting Each variable has a type in java. Each data type has a size (number of bits used by that type). byte < short < (char)< int < long < float < double Each data type has a range of values that it can hold. This range of values is based on the size of the data type. The byte, long, float and double are signed. The char type is unsigned. We cannot assign a byte or a short to a char and vice versa.

2) Casting example in java The size of byte data type is 8 bits. The range of values that can be coded using 8 bits is the following: from 0 to 127. We can imagine that each type is a bag. The bags are of different sizes. The bag associated to the byte type is the smallest one. The bag associated to the double type is the biggest one. A bag can be either full or partially filled.

3) Casting in java: problem Let’s imagine that we have a big bag and a small one. The big bag is filled up with items. What happens when we put the content of the big bag inside the small one? The answer is that we cannot do that. The same problem occurs when we try to assign a bigger type value to a smaller type variable. int a = 100; byte b = a; Here we try to assign an int value (the content of the variable a) to a variable of type byte. In this case, the java compiler will complain.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.