DEV Community

Arun Kumar
Arun Kumar

Posted on

🌟 What is Casting in Java?

Today my trainer on conducting mcq test send a question paper to write the answer of this question after completing test 25 out of 18.
After the test class going on casting on java.

Casting means converting one data type into another. Java is a strongly-typed language, so sometimes you can’t directly assign values of one type to another. Casting helps you make that conversion.

🎯 Types of Casting in Java
There are two main types of casting:

1️⃣ Widening Casting (Automatic Conversion)
Also called upcasting.

Java automatically converts a smaller type into a larger type.

βœ… Safe because there’s no data loss.

πŸ‘‰ Example:

public class WideningExample {
public static void main(String[] args) {
int num = 100;
double d = num; // automatic casting (int β†’ double)
System.out.println("Integer value: " + num);
System.out.println("Double value: " + d);
}
}
Output:

Integer value: 100

Double value: 100.0

2️⃣ Narrowing Casting (Manual Conversion)
Also called downcasting.

You need to manually tell Java to convert a larger type into a smaller type.

⚠️ Risky because data may be lost.

πŸ‘‰ Example:

public class NarrowingExample {
public static void main(String[] args) {
double d = 99.99;
int num = (int) d; // manual casting (double β†’ int)
System.out.println("Double value: " + d);
System.out.println("Integer value: " + num);
}
}
Output:

Double value: 99.99

Integer value: 99

Top comments (0)