Java Type Casting

The process of converting one data type to another data type is called casting.

Type casting in Java is the process of converting one data type into another. This is commonly used in scenarios where you need to handle data of different types, or to explicitly instruct the compiler to convert a value.

There are two main types of casting in Java:

1. Widening (Implicit) Casting

Also known as automatic casting, this occurs automatically when a smaller data type is converted into a larger data type.

Order of Data Types (Widening Path)

Implicit Data Type

Example:


public class TypeCastingExample {
    public static void main(String[] args) {
        int num = 10;         // Integer value
        double result = num;  // Automatic casting to double
        System.out.println("Integer value: " + num);
        System.out.println("Widened to double: " + result);
    }
}

Output:

Integer value: 10 Widened to double: 10.0

2. Narrowing (Explicit) Casting

Also known as manual casting, this requires explicit instruction because data loss is possible when converting a larger type to a smaller type.

Order of Data Types (Narrowing Path)

Explicit Data Type

Example:


public class TypeCastingExample {
    public static void main(String[] args) {
        double decimalNumber = 12.25;  // Double value
        int wholeNumber = (int) decimalNumber;  // Manual casting to int
        System.out.println("Double value: " + decimalNumber);
        System.out.println("Narrowed to int: " + wholeNumber);
    }
}

Output:

Double value: 12.25 Narrowed to int: 12

Java Type Casting – Interview Questions

Q 1: What is type casting in Java?
Ans: Type casting converts one data type into another.
Q 2: How many types of data types are there in Java?
Ans: Two: Widening and Narrowing.
Q 3: What is widening casting?
Ans: Automatic conversion from smaller to larger data type.
Q 4: What is narrowing casting?
Ans: Manual conversion from larger to smaller data type.
Q 5: Is data loss possible in type casting?
Ans: Yes, during narrowing casting.

Java Type Casting – Objective Questions (MCQs)

Q1. What is type casting in Java?






Q2. Which of the following is automatic type casting (also known as implicit casting) in Java?






Q3. Which of the following is a valid example of explicit type casting (also known as manual casting) in Java?






Q4. What will be the result of the following Java code?

int x = 20;
double y = 3.5;
int result = x + (int) y;
System.out.println(result);






Q5. What happens when you try to cast a larger primitive data type to a smaller primitive data type in Java, like double to int?






Related Java Type Casting Topics