Type casting in Java is the process of converting a data type to another data type in both ways, manually (explicit) or automatically (implicit). There are two types of type casting, widening and narrowing.

Widening

Widening converts smaller data type is converted to a larger data type. This type of casting is safe and does not lead to data loss.

int num = 10;
double d = num; // implicit type casting: int to double
System.out.println(d); 
10.0

Narrowing

Narrowing casting, it is often done manually by the programmer. It happens when a larger data type is converted to a smaller data type. It may cause data loss.

double d = 10.5;
int num = (int) d; // explicit type casting: double to int
System.out.println(num); 
 
10

Casting floating point number to integer number leads to the lose of fractional part.

Type casting between reference types

Type casting can also occur between reference types, primarily involving class hierarchies and interfaces. There are two types of type casting between reference types.

Upcasting

Converting a subclass type to a superclass type.

class Animal {}
class Dog extends Animal {}
 
Animal animal = new Dog(); // upcasting: Dog to Animal
// Animal animal = (Animal) new Dog();

Here, the upcasting is implicit, without a cast operator.

Downcasting

Converting a superclass type to a subclass type. This is explicit and requires a cast operator.

Animal animal = new Dog();
Dog dog = (Dog) animal; // downcasting: Animal to Dog

Dynamic method dispatch

Type casting between reference types is often used in Dynamic Method Dispatch (Runtime Polymorphism), where which method will be called for an object will be determined at runtime.

class A {
	public void displayA {
		System.out.println("A displayed");
	}
}
 
class A extends B {
	public void displayB {
		System.out.println("B displayed");
	}
}
 
public class Demo {
	public static void main(String[] args) {
		A obj = new B(); // upcasting: B to A
		obj.displayA();
		
		obj.displayB(); // compilation error
	}
}
A displayed

Here, the displayB() method cannot be called because the obj is referenced to A. To call the displayB() method, the object has to be casted to B.

public class Demo {
	public static void main(String[] args) {
		A obj = new B(); // upcasting: B to A
		// obj.displayA();
		
		B objCast = (B) obj; //downcasting: from A to B
		objCast.displayB(); 
	}
}
B displayed

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaType_CastingWideningNarrowingUpcastingDowncasting