Type Casting in Java

Type Casting in Java

9 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Jun 12, 2024 14:49 IST

Have you ever wondered how Java handles different data types and ensures smooth operations between them? This is where type casting comes in. It allows the conversion of variables from one data type to another, either automatically (implicit casting) or manually (explicit casting), to facilitate efficient and flexible programming. Let's understand more!

Type casting in Java is the process of converting one data type into another. This is important when you need to perform operations on variables of different types or when a method requires a specific type. Type casting ensures that the data fits the required type for the operation or method.

Check out Java Courses Here!

Table of Content

Types of Type Casting in Java

  • Implicit Casting (Widening and Upcasting)
  • Explicit Casting (Narrowing and Downcasting)

Widening and Narrowing are considered as primitive type casting while upcasting and downcasting are considered as reference type casting!

1. A. Implicit Casting (Widening)

Implicit casting, also known as widening casting, is the automatic conversion of a smaller primitive data type to a larger primitive data type. The Java compiler performs this type of casting without any explicit instructions from the programmer. It is safe and does not result in data loss because the target type can accommodate the range and precision of the source type.

Common conversions include byte to short, int, long, float, double, and others.

Think of implicit casting like pouring water from a small cup into a larger cup. The larger cup can easily hold the water without any spillage, similar to how a larger data type can accommodate the value of a smaller data type.

Syntax

largerType variableName = smallerTypeValue;

For Example,


 
public class ImplicitCastingExample {
public static void main(String[] args) {
int myInt = 10;
double myDouble = myInt; // Implicit casting from int to double
System.out.println("Integer value: " + myInt); // Outputs: Integer value: 10
System.out.println("Double value: " + myDouble); // Outputs: Double value: 10.0
}
}
Copy code

Output

Integer value: 10
Double value: 10.0

The program prints both the integer and the double values. The double value shows a decimal point, indicating that it has been successfully converted from an integer.

1. B. Implicit Casting (Upcasting)

Implicit casting, also known as upcasting in the context of object-oriented programming, is the automatic conversion of a subclass type to a superclass type. This type of casting is done by the Java compiler without explicit instructions from the programmer. Upcasting is safe because the subclass object inherently possesses the properties and behaviours of the superclass.

Think of upcasting like treating a specific type of fruit, such as an apple, as a more general category, like fruit. You can refer to an apple as a fruit without any issue because an apple is a type of fruit. Similarly, you can refer to a subclass object (like Dog) as a superclass type (like Animal) because it inherits the characteristics of the superclass.

Syntax

SuperClass superClassReference = subClassObject;

For Example,


 
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
void bark() {
System.out.println("Dog barks");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Dog myDog = new Dog();
Animal myAnimal = myDog; // Implicit upcasting from Dog to Animal
myAnimal.makeSound(); // Outputs: Bark
// myAnimal.bark(); // This would cause a compile-time error
}
}
Copy code

Output

Bark

The line myAnimal.makeSound(); calls the overridden makeSound method in the Dog class, resulting in the output "Bark".

2. A. Explicit Casting (Narrowing)

Explicit casting, also known as narrowing casting, is the process of manually converting a larger primitive data type to a smaller primitive data type. This type of casting requires explicit syntax because it can lead to data loss or precision loss. The programmer must instruct the compiler to perform this conversion.

Think of explicit casting like pouring water from a larger bucket into a smaller cup. You need to be careful because some water might spill, similar to how some data might be lost when converting from a larger to a smaller type.

Syntax

smallerType variableName = (smallerType) largerTypeValue;

For Example,


 
public class NarrowingCastingExample {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Explicit casting from double to int
System.out.println("Double value: " + myDouble); // Outputs: Double value: 9.78
System.out.println("Integer value: " + myInt); // Outputs: Integer value: 9
}
}
Copy code

Output

Double value: 9.78
Integer value: 9

The program prints both the original double value and the converted int value. The integer value shows 9, indicating that the fractional part (0.78) was truncated during the conversion, demonstrating potential data loss.

2. B. Explicit Casting (Downcasting)

Explicit casting, also known as downcasting, is the process of converting a reference of a superclass type to a reference of a subclass type. This type of casting requires explicit syntax because it can lead to a ClassCastException at runtime if the object being cast is not actually an instance of the subclass. The programmer must instruct the compiler to perform this conversion.

Think of downcasting like identifying a general category (e.g., a vehicle) as a specific type (e.g., a car). You need to be sure that the vehicle is actually a car before you treat it as one, otherwise, you might run into problems (like trying to start a bicycle with a car key).

Syntax

SubClass subClassReference = (SubClass) superClassReference;

For Example,


 
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
void bark() {
System.out.println("Dog barks");
}
}
public class DowncastingExample {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
myAnimal.makeSound(); // Outputs: Bark
// Explicit Downcasting
if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal; // Downcasting
myDog.bark(); // Outputs: Dog barks
}
}
}
Copy code

Output

Bark
Dog barks

The line myAnimal.makeSound(); outputs "Bark" because the myAnimal reference, which is upcast to Animal, actually refers to a Dog object. The line myDog.bark(); outputs "Dog barks" after downcasting myAnimal back to Dog.

Real-World Applications of Type Casting in Java

Application Area

Type of Casting

Description

Example

Data Processing

Implicit (Widening)

Used to integrate and convert data from different sources into a consistent format.

ETL (Extract, Transform, Load) processes in data warehousing.

Polymorphism in OOP

Explicit (Downcasting)

Enables a method to process objects differently based on their runtime type.

Graphic design software handling different shapes (e.g., circle, rectangle).

Database Applications

Implicit (Widening)

Handles SQL query results and converts SQL data types to Java data types.

ResultSet handling in JDBC to fetch data from databases.

Network Communication

Explicit (Downcasting)

Processes different types of data packets and messages.

Protocol implementation handling various network messages.

API Development

Explicit (Downcasting)

Casts generic data structures to specific types for processing.

JSON parsing using libraries like Jackson or Gson.

User Interface Development

Explicit (Downcasting)

Handles various component types and event sources in UI frameworks.

Event handling in GUI frameworks like Swing or JavaFX.

Financial Applications

Implicit (Widening)

Ensures accurate operations in calculations with mixed data types.

Currency conversion calculations in financial software.

 

Advantages of Type Casting in Java

  • Type casting enables polymorphism, allowing methods to operate on objects of various types through superclass references, enhancing code reusability.
  • Efficient memory usage is achieved by converting data to appropriate types and optimizing performance and storage.
  • Ensures compatibility with older APIs and libraries, facilitating integration with existing systems.
  • Downcasting allows access to subclass-specific methods, enabling dynamic method calls and implementation of design patterns.
  • Enables data processing and manipulation from different sources by converting it to the required types.

Difference Between Type Casting and Type Conversion in Java

Aspect

Type Casting

Type Conversion

Definition

Explicitly converting a variable from one data type to another.

Automatically converting a variable from one data type to another.

Initiated By

Programmer

Compiler

Syntax

Requires explicit syntax, e.g. (int) myDouble.

Implicit, done automatically by the compiler.

Types

Includes explicit (narrowing) and implicit (widening).

Only implicit (widening) conversion.

Use Cases

Needed when converting larger types to smaller types or superclass references to subclass references.

Automatically happens when converting smaller types to larger types.

Risk of Data Loss

High, especially during narrowing conversion (e.g. double to int).

Low, as it involves widening conversions (e.g. int to double).

Common Usage

Downcasting objects, converting floating-point numbers to integers.

Widening primitive data types, such as converting int to double.

Applicability

Used for both primitive and reference types.

Primarily used for primitive types.

Thus, Type casting is a fundamental concept in Java that enhances flexibility and efficiency in programming. It allows the conversion of one data type to another, enabling polymorphism, efficient memory management, and interoperability with legacy code. 

Types of Constructors in Java
Types of Constructors in Java
Have you ever wondered how objects in Java are initialized? There are three types of constructors that handle this, i.e., default constructors provide automatic, no-argument initialization; parameterized constructors allow for...read more

Control Statements in Java - About and Types
Control Statements in Java - About and Types
Have you ever wondered how Java manages the flow of its programs so efficiently? The three types of control statements, namely decision-making statements, looping statements, and jump statements, allow Java...read more

All About Java Operators
All About Java Operators
Have you ever wondered how Java performs calculations, makes decisions, or manipulates data so efficiently? This is where Java operators come into play. Operators in Java are special symbols that...read more

Understanding Variables in Java
Understanding Variables in Java
Have you ever wondered how data is stored and manipulated in Java programs? Variables in Java are the answer, acting as containers for data values. Each variable is defined with...read more

FAQs

What is type casting in Java?

Type casting in Java is the process of converting a variable from one data type to another. This can be done either implicitly or explicitly, depending on the types involved and the direction of the conversion.

What are the main types of type casting in Java?

The main types of type casting in Java are:

  • Implicit (Widening) Casting: Automatically converting a smaller primitive type to a larger primitive type.
  • Explicit (Narrowing) Casting: Manually converting a larger primitive type to a smaller primitive type.
  • Upcasting: Implicitly converting a subclass type to a superclass type.
  • Downcasting: Explicitly converting a superclass type to a subclass type.

How does implicit (widening) casting work?

Implicit casting automatically converts a smaller primitive type to a larger one without explicit instructions from the programmer. For example, int to double.

What is explicit (narrowing) casting?

 Explicit casting requires explicit syntax to convert a larger primitive type to a smaller one, which may lead to data loss. For example, double to int.

What is upcasting in Java?

Upcasting is the process of converting a subclass type to a superclass type implicitly. It is safe because the subclass inherits properties and methods from the superclass.

What is downcasting in Java?

Downcasting is the explicit conversion of a superclass type to a subclass type. It requires explicit casting and can throw a ClassCastException if the object is not actually an instance of the subclass.

Why do we need type casting in Java?

Type casting is needed to handle conversions between different data types, enable polymorphism, ensure compatibility with legacy code, and optimize memory usage. It allows for more flexible and reusable code.

What are the risks of explicit casting?

Explicit casting can lead to data loss, precision loss, and runtime exceptions such as ClassCastException. Careful checks using operators like instanceof are recommended to ensure safety.

Can we cast any type to any other type?

 No, type casting can only occur between compatible types. For primitives, this means numeric types can be cast among themselves. For objects, casting is limited to objects within the same inheritance hierarchy.

How do I handle ClassCastException during downcasting?

To handle ClassCastException, use the instanceof operator to check the type before performing the cast.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio