Typecasting in Java: A Detailed Explanation with Example

Typecasting in Java: A Detailed Explanation with Example

10 Sep 2024
Beginner
213 Views
23 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

Typecasting in Java

Type Casting in Java, commonly known as type conversion, is an important technique that allows us to transform one data type into another. It is useful when we need to execute operations on several data types or when we wish to save a value from one data type in another. Type casting in Java is the process of transforming variables between multiple data types, which is necessary for flexible programming.

In the Java tutorial, we will look into several aspects of Typecasting in Java, including types of typecasting, implicit type casting & explicit type casting, handling data loss and precision issues, typecasting between object references, and many more.

Accelerate your development career with our comprehensive Java Full Stack Developer Training—join now!

What is Typecasting in Java?

Typecasting in Java is the process of transforming the value of one data type (such as an integer [int], float, or double) to another. The compiler conducts the automated conversion while the programmer does the manual conversion. To utilize a variable in a certain fashion in automatic conversion, we must explicitly instruct the Java compiler to transform the variable from one data type to another.

Syntax

<datatype> variableName = (<datatype>) value;
Read More
Data Types in Java - Primitive and Non-Primitive Data Types
Types of variables in Java with examples: Local, Instance & Static

Types of Typecasting

There are two types of typecasting in Java that are following below:

  1. Widening Type Casting
  2. Narrowing Type Casting

What is Implicit Typecasting?

Implicit Typecasting is also known as widening typecastingWidening typecasting is the technique of converting a lower data type into a higher data type. This approach is computerized and safe, as there is no chance of data loss. This form of conversion and casting in Java occurs when:

  • The source data type should be less than the destination data type.
  • The two data types should be appropriate.

Syntax

larger_data_type variable_name = smaller_data_type_variable;

Implicit Typecasting

Example: Transforming int data type to double data type

class Main {
  public static void main(String[] args) {
    // create int data type variable
    int num = 5;
    System.out.println("The integer number is: " + num);

    // changing into double data type
    double data = num;
    System.out.println("The double number is: " + data);
  }
}

Output

The integer number is : 5
The double number is : 5.0

Explanation

In this above example,
  • We have taken a variable num that stores the value 5 and printed it to the console.
  • After that, we converted the num variable to the double data type and stored it as a data variable, and the result 5.0 was printed in the console.

Limitations of Implicit Typecasting

There are several limitations for Implicit type casting that are followed below:

1. Unpredictable Behavior

  • Loss of precision when converting complex types (e.g., floats to integers).
  • Unintended conversions can lead to bugs (e.g., string concatenation instead of numeric addition).

2. Reduced Code Clarity

  • Harder to read and debug due to conversions happening behind the scenes.
  • Over-reliance on implicit casting can lead to less robust code.

3. Performance Overhead

  • It may impose a minor performance cost owing to runtime type determination.

4. Compatibility Issues

  • Cross-language portability problems due to different types of constraint rules.
  • Changes in language versions may alter implicit casting behavior.

What is Explicit Typecasting?

Explicit Typecasting is also known as narrowing typecastingNarrowing type casting is the method of converting a bigger data type into a smaller data type. The narrowing type casting is risky because the lower data type's limited range of allowable values may result in data loss. The cast operator aids in explicit casting.

Syntax

smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

Explicit Typecasting

Example: transforming double data type to int data type

class Main {
  public static void main(String[] args) {
    // creating double type variable
    double num = 8.99;
    System.out.println("The double value is: " + num);

    // transform into int type
    int data = (int)num;
    System.out.println("The integer value is : " + data);
  }
}

Output

The double value: 8.99
The integer value: 8

Explanation

In the above example,

  • We have declared a double variable name num, stored the value 8.99, and printed it.
  • After that, we declare an int variable named data, and int data = (int)num; will convert the double value to int value and the output 8 pint in the console.

Handling Data loss and Precision Issues In Explicit Typecasting

Handling data loss and precision concerns in explicit typecasting necessitates careful conversion management to maintain correctness and avoid unexpected outcomes. Here are a few strategies:

1. Check for Range Compatibility

Before casting, make sure that the target type can handle the range of values from the source type to avoid overflow or underflow.

2. Round or Truncate as Needed

When casting from a floating-point type to an integer, decide whether to round, floor, or truncate the value explicitly to control how precision loss is handled.

3. Use Larger Data Types When Necessary

If you anticipate precision loss, consider using a larger data type that can hold the value without losing significant digits (e.g., using double instead of float).

4. Use Explicit Conversion Functions

Instead of relying on casting, use explicit conversion functions or methods provided by the language that handle precision and data loss more gracefully, such as Math.round() in Java, for more precise control.

5. Validate Data Post-Conversion

After casting, validate the converted data to ensure it meets the expected range and precision. This can involve checking for significant digits or comparing against the original value.

Example: Transforming int data type to String data type

class Main {
  public static void main(String[] args) {
    // creating int type variable
    int num = 8;
    System.out.println("The integer value is: " + num);

    // converts int to string type
    String data = String.valueOf(num);
    System.out.println("The string value is: " + data);
  }
}

Output

The integer value is: 8
The string value is: 8

Explanation

In this example,
  • We have created a int data type variable and store value in num variable.
  • After that we declare String data type variable and String data = String.valueOf(num); convert the int value to string data value.
Read More
while Loop in Java
for Loop in Java: Its Types and Examples
What is String in Java - Java String Methods & Type (Examples)

Type Casting Between Object Reference

Type casting between object references in Java involves converting an object of one type into another. This process is essential when dealing with inheritance and interfaces in Java. Type casting between object references can be categorized into two types:

  1. Upcasting
  2. Downcasting
Read More
Single Inheritance in Java
Multiple Inheritance in Java
Hybrid Inheritance in Java

1. Upcasting

Converting a subclass reference to a superclass reference. This type of casting is always safe and implicit (automatic). Upcasting is generally used when you wish to treat a subclass object as an instance of its superclass, which is usually done to take advantage of polymorphism.

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

class Dog extends Animal {
    void makeSound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Animal animal = dog; // Upcasting: Dog to Animal
        animal.makeSound();  
    }
}

Output

 Bark

Explanation

In this above example, we have created a parent class Animal with a single method and a child class Dog with its own method bark(), which inherits from Animal.
  • In the main method, Creates a new Dog object and assign it to the variable dog.
  • Animal animal = dog; This is upcasting. The Dog object is assigned to an Animal reference variable animal. This is possible because Dog is a subclass of Animal.
  • Calls the makeSound() method on the animal object. and print the result.

2. Downcasting

It is the method of converting a superclass reference back to a subclass reference. This type of casting must be done explicitly and can be unsafe, potentially leading to a ClassCastException at runtime. Downcasting is used when you need to access subclass-specific methods or fields that are not available in the superclass.

Example

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

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

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog(); // Upcasting
        Dog dog = (Dog) animal;    // Downcasting
        dog.bark();                
    }
}

Output

Bark

Explanation

In this above example, we have created a parent class Animal with a single method makeSound() and a child class Dog with its own method bark(), which inherits from Animal.

  • In the main method, created a Dog object and stored it as an animal variable referenced by the Animal known as upcasting.
  • Dog dog = (Dog) animal; is downcasting. We are casting the Animal reference animal back to a Dog reference dog.
Note: To avoid 'ClassCastException', it's a good practice to check the type before downcasting using the 'instanceof' operator.

Example

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

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

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog(); // Upcasting

        if (animal instanceof Dog) {
            Dog dog = (Dog) animal; // Safe downcasting
            dog.bark();            
        } else {
            System.out.println("Not a Dog");
        }
    }
}

Output

Bark

Explanation

In the above example, we have created a parent class Animal with a single method makeSound() and a child class Dog with its own method bark(), which inherits from Animal.

  • In the main method, created a Dog object and stored it as an animal variable referenced by the Animal known as upcasting.
  • In if statement, we use instanceof operator to check if the referenced by animal is actually an instance of Dog.
  • Inside the if statement, Dog dog = (Dog) animalis downcasting. We are casting the Animal reference animal back to a Dog reference dog.
Read More
Top 50 Java MCQ Questions
Java Multithreading Interview Questions and Answers 2024
Top 50+ Java 8 Interview Questions & Answers 2024
Summary

In the above article, we have thoroughly explored the topic of typecasting in Java. I hope this article will definitely help you clear your doubts regarding typecasting and enhance your programming skills. Understanding both implicit and explicit typecasting is essential for smoothly managing type conversions. If you are a beginner in Java programming, enroll in our Full Stack Java Developer Course to grab the comprehensive step-by-step guide to Java.

FAQs

Q1. What is type casting and type conversion?

Type casting is explicit conversion between compatible data types by the programmer, often involving potential data loss. Type conversion is implicit conversion between compatible data types performed by the compiler without programmer intervention.

Q2. What is the difference between casting and converting?

Casting is an explicit type conversion controlled by the programmer, often with potential data loss. Converting is an implicit type of conversion handled by the compiler without explicit code, which is usually safe.

Q3. Which is faster, CAST or convert?

CAST is generally slightly faster than CONVERT. However, the difference is negligible in most cases.   




Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Software Architecture and Design TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Solution Architect Certification TrainingSep 22SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Full-Stack .NET Developer Certification TrainingOct 06SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Angular Certification TrainingOct 06SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 13SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 13SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core ProjectOct 13SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Azure Developer Certification TrainingOct 27SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this