Casting in Java
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 dont 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.
But, w said above that the byte type can hold the value 100.
Here, the java compiler complains because there is a chance that the variable a contains a
value that cannot be held by a variable of byte type.
We can imagine here that the bag associated to the int type is partially filled. But, it can be
totally filled in the future when our app runs.
So, we havent made a mistake.
Here where comes the necessity of casting.
In fact, we can use casting here to tell the compiler to trust us and not to complain.
The code becomes like this:
int a = 100;
byte b = (byte) a;
So, the casting in java is related to assignment.
It is done by putting the type of the variable on the left hand side of the assignment between
parentheses.
This is the only way to do casting.
This operation is problematic because it may cause a loss of information when making.
This is why we have to perform the java cast in this situation.