Casting variables in Java

Casting a varibale in java is converting the type of a variable from one datatype to another.

There are two types of casting:

  1. explicit casting;
  2. implicit casting.

Explicit casting

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;

Implicit casting

Implicit casting in Java is when you assign a variable of a lower (or child) type to a greater (or parent) type. A conversion is  automatically made by the compiler without the programmer’s intervention.

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;


Casting primitives

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.

Primitives casting in Java

Primitives casting in Java