Casting a varibale in java is indicating to the compiler that a variable of type A will be used as an other type B. There are two types of casting, implicit and explicit.
Implicit casting in Java is when you assign a variable of a lower (or child) type to a greater (or parent) type.
Examples of implicit casting:
// example 1 : a was implicitly casted from int to double int a = 10; double d=a; // example 2 : student was implicitly casted from Student to Person // we suppose that Student is a subclass of Person Student student= new Student(); Person person = student;
Explicit casting in Java is when you explicitly indicate to the compiler the target type you want to convert the value of your variable to (otherwise your code will not compile).
It is like if you tell the compiler : Trust me, my varibale can be cast to the target type !
The source data type must be compatible with the target data type at runtime (when you execute the program). If not, you will get a ClassCastException.
Examples of explicit casting:
// 256.1234f will be converted to int and the // digits after the period (.) will be lost float f = 256.1234f; int i = (int)f; // p is converted to Student datatype // Student must be a sub-type of Person Person p= new Person(); Student s = p;
Java allows primitive types to be cast implictly from lower to higher data types . For explicit cast of primitives, you have to be careful with the loss of precision and varibale truncating when you cast higher to lower datatypes (Example : from double to int).
The following is a summary of what are the implicit and explicit casts allowed for primitive types in Java.