CASTING

Casting in Java is the process of converting a variable from one type to another. This can involve both primitive types and reference types. Casting is essential when you need to interact with different types of data, especially when dealing with inheritance and interfaces.

1. Types of Casting

There are two main types of casting in Java:

2. Primitive Type Casting

Primitive type casting involves converting one primitive data type into another. There are two kinds of primitive type casting:

Implicit (Widening) Casting

This happens automatically when converting a smaller type to a larger type. For example, byte to int or int to double. This is safe because there is no loss of information.

int num = 100;
double d = num; // Implicit casting: int to double
System.out.println(d); // Output: 100.0

Explicit (Narrowing) Casting

This requires explicit syntax to convert a larger type to a smaller type, as it can result in data loss.

double d = 100.04;
int num = (int) d; // Explicit casting: double to int
System.out.println(num); // Output: 100

3. Reference Type Casting

Reference type casting is used with objects and can be categorized as: