Java Type Casting


Type casting in Java is the process of converting one data type into another. It allows you to perform operations between different data types without errors. Since Java is a strongly typed language, you cannot directly assign a value of one type to another incompatible type unless it’s explicitly or implicitly converted. Understanding type casting is essential for data manipulation, mathematical operations, and handling mixed-type expressions efficiently.

What is Type Casting in Java?

Type casting means assigning a value of one data type to a variable of another type. For example, you can assign an int value to a double variable, or you can convert a double value back into an int. Java automatically performs certain conversions, while others must be done manually using explicit casting.

There are two main types of type casting in Java:

  1. Widening Type Casting (Automatic Conversion)

  2. Narrowing Type Casting (Manual Conversion)

Widening Type Casting (Implicit Conversion)

Widening type casting happens automatically when a smaller data type is converted into a larger data type. It is also called automatic type conversion. Java performs this conversion safely because no data is lost during the process.

For example, an int can be converted into a double, or a float can be converted into a double automatically.

Syntax Example:

int num = 10;
double result = num; // int to double conversion
System.out.println(result);

Explanation:
Here, the integer 10 is automatically converted to a double 10.0 by Java. You don’t need to write any special code for this conversion.

Data Type Order (from smaller to larger):
byte → short → int → long → float → double

This sequence shows how data types can automatically widen from smaller to larger sizes.

Narrowing Type Casting (Explicit Conversion)

Narrowing type casting is the process of converting a larger data type into a smaller one. It must be done manually because there’s a risk of data loss. You need to use parentheses to specify the target data type.

Syntax Example:

double num = 12.56;
int result = (int) num; // double to int conversion
System.out.println(result);

Explanation:
In this case, the decimal part 0.56 is lost because an int cannot store fractional values. That’s why explicit casting is required.

Important Note:
Narrowing can lead to data truncation or overflow if the value exceeds the target type’s range.

Example of Both Widening and Narrowing

Let’s look at an example that shows both conversions:

public class TypeCastingExample {
    public static void main(String[] args) {
        int a = 25;
        double b = a;       // Widening (Automatic)
        System.out.println("After Widening: " + b);

        double c = 89.75;
        int d = (int) c;    // Narrowing (Manual)
        System.out.println("After Narrowing: " + d);
    }
}

Output:

After Widening: 25.0
After Narrowing: 89

This example clearly shows how Java performs both types of conversions depending on the situation.

Type Casting Between Non-Primitive Data Types

Type casting also exists between objects in Java. It’s mainly used when working with inheritance. If a class is a subclass of another, it can be cast between parent and child types.

There are two types:

  1. Upcasting (Implicit)

  2. Downcasting (Explicit)

Upcasting (Automatic)

Upcasting happens when a subclass object is assigned to a superclass reference. This type of casting is done automatically because every subclass object is also an instance of its superclass.

Example:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal obj = new Dog(); // Upcasting
        obj.sound(); // Works fine
    }
}

Explanation:
Here, the Dog object is assigned to an Animal reference. Java performs this automatically. However, only the methods available in Animal can be accessed.

Downcasting (Manual)

Downcasting happens when a superclass reference is converted back into a subclass reference. This conversion must be done explicitly using casting syntax.

Example:

Animal a = new Dog(); // Upcasting
Dog d = (Dog) a;      // Downcasting
d.bark();             // Now subclass method can be accessed

Important:
Downcasting can cause a ClassCastException if the object being cast is not actually an instance of the subclass.

Type Casting Between char and int

Java allows type conversion between characters and integers since characters are stored as Unicode values. For example:

char ch = 'A';
int code = ch; // char to int
System.out.println("ASCII value of A: " + code);

int num = 66;
char letter = (char) num; // int to char
System.out.println("Character for 66: " + letter);

Output:

ASCII value of A: 65
Character for 66: B

Common Mistakes in Type Casting

  1. Forgetting to use parentheses while performing narrowing conversion.

  2. Casting incompatible reference types (for example, casting unrelated classes).

  3. Ignoring data loss during narrowing from floating-point to integer.

  4. Attempting to downcast without checking object type using instanceof.

Always use explicit casting carefully and validate types when working with objects.

Summary of Java Type Casting

Type casting is an important concept in Java that allows flexibility when dealing with different data types.

  • Widening (automatic) happens safely without data loss.

  • Narrowing (manual) requires explicit casting and may lead to data loss.

  • Upcasting and Downcasting are used with objects during inheritance.
    By understanding how Java handles type conversions, you can write more efficient and error-free programs.


Practice Questions

  1. Write a Java program that performs automatic type conversion from int to double and prints both the original and converted values.

  2. Create a Java program that demonstrates explicit type conversion by converting a double value to an int and printing the result after truncation.

  3. Write a program that declares a byte variable, assigns it a small value, and converts it into an int, float, and double step by step, displaying the result after each conversion.

  4. Develop a Java program that shows the loss of data during narrowing type casting by converting a large int value into a byte and printing the final output.

  5. Create a Java program that reads a floating-point number from the user, casts it to an integer, and prints both the original and converted values.

  6. Write a Java program that demonstrates type casting between char and int. Convert a character to its ASCII value and then convert an integer back to a character.

  7. Create a program that declares a long variable and assigns it to a float variable. Print the values to show how precision changes after conversion.

  8. Write a Java program that performs both widening and narrowing conversions in one program — first convert an int to a double, and then convert that double back to an int.

  9. Develop a program that demonstrates upcasting and downcasting using two classes, for example, a superclass Vehicle and a subclass Car, to show how object type conversion works.

  10. Create a Java program that takes a double input representing temperature in Celsius, casts it to an integer to remove decimal precision, and displays both the original and casted values.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top