Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of Type Casting
3.
Types of Type Casting
3.1.
Widening Type Casting
3.2.
Narrowing Type Casting
4.
Types of Explicit Casting
4.1.
Explicit Upcasting
4.2.
Explicit Downcasting
5.
Frequently Asked Questions
5.1.
What happens if I try to narrow cast a larger value into a smaller type and it doesn't fit?
5.2.
Can I use type casting with non-primitive data types in Java?
5.3.
Is explicit casting safe?
6.
Conclusion
Last Updated: Apr 5, 2024
Medium

Type Casting in Java

Author Ravi Khorwal
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

In Java, typecasting is used to convert one data type to another.This is useful when you have data in one form but need it in another for certain operations. By doing typecasting, you're giving clear instructions to the Java compiler to see a piece of data as a different type, making it fit for the task you need to do.

Type Casting in Java

In this article, we're going to learn how this works, different ways to do typecasting in Java and see examples to help make it clear.

Syntax of Type Casting

To use type casting in Java, you need to follow a simple formula in your code. It looks like this: you write the new type that you want your data to be in, put it in parentheses, and then put the variable or value you're changing next to it. This tells Java, "Hey, I know this data looks like this right now, but I need you to treat it as this other type for a moment."

For example: if you have a number that's an integer (a whole number) but you need it to be a double (a number that can have decimal points), you would write it like this:

int myInteger = 100;
double myDouble = (double) myInteger;


In this line of code, (double) is the casting operator telling Java to treat myInteger, which is originally an int, as a double. So now, myDouble will treat the value 100 not just as a simple whole number but as a double, which means it can work with decimal operations too.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Type Casting

In Java, type casting falls into two main categories: widening type casting and narrowing type casting. 

Widening Type Casting

Widening type casting, also known as implicit casting, is the safer and more automatic of the two types. It's when you go from a smaller data type to a larger one, like turning an int into a long. Java can do this on its own because there's no risk of losing any data; the larger type has enough space to hold all the information from the smaller type.

For Example:

int myInt = 9;
long myLong = myInt;  // Automatically widens the int to a long


In this case, myInt is an int, which is a smaller data type, and myLong is a long, which is larger. Java automatically widens myInt to fit into myLong without needing any special instructions.

Narrowing Type Casting

Narrowing type casting, or explicit casting, is a bit trickier. This is when you're going from a larger data type to a smaller one, like turning a double into an int. Because you're moving to a smaller type, there's a risk of losing some information, so Java needs you to be explicit about it. You have to tell Java directly that you understand the risk and still want to go ahead.

For Example -: 

double myDouble = 9.78;
int myInt = (int) myDouble;  // Explicitly narrows the double to an int


In this example, myDouble is a double, which is a larger data type that can hold decimal values. myInt is an int, which can only hold whole numbers. By using (int) before myDouble, you're telling Java, "I know myDouble is a double, but please treat it as an int." This operation might cut off the decimal part, so it's something you do knowingly.

Types of Explicit Casting

Explicit casting in Java is crucial when you need precise control over how your data is treated, especially when converting from a larger to a smaller data type. Within explicit casting, there are two primary operations to understand: explicit upcasting and explicit downcasting.

Explicit Upcasting

Upcasting is bit of a misnamed because it implies moving up to a larger data type, which usually doesn't require explicit casting. However, in terms of class hierarchies (when dealing with objects, not primitive types), upcasting refers to treating a subclass object as an instance of one of its superclass types. This is generally safe and automatic because the subclass has all the methods and properties of the superclass. Here's an example to illustrate upcasting in the context of object-oriented programming:

class Animal {}
class Dog extends Animal {}
Animal myAnimal = new Dog();  // This is upcasting


In this code, Dog is a subclass of Animal. By assigning a Dog object to an Animal reference, we're upcasting. This is usually implicit and safe because a Dog is an Animal.

Explicit Downcasting

Downcasting is where you need to be explicit. It's about treating an object of a superclass as an object of one of its subclasses. Since this involves more specific types, there's a risk of errors, so Java requires explicit action.

For example -: 

Animal myAnimal = new Dog();  // Upcasting is implicit here
Dog myDog = (Dog) myAnimal;  // Explicitly downcasting back to Dog


In this example, myAnimal is initially an Animal type but actually holds a Dog object. To access Dog-specific features on myAnimal, you need to downcast it back to Dog. This requires explicit casting with (Dog) to tell Java that you're sure myAnimal can be treated as a Dog.

Note -: Downcasting needs to be done carefully because if the object being downcasted isn't actually an instance of the subclass, it will throw a ClassCastException. That's why Java insists on explicit casting here, as a way of making you double-check what you're doing.

Frequently Asked Questions

What happens if I try to narrow cast a larger value into a smaller type and it doesn't fit?

If you narrow cast a value that's too big for the smaller type, Java will not stop you, but the result might not be what you expect. For example, if a large integer is cast to a byte, Java will keep only the lower 8 bits of the integer, which might change the value completely.

Can I use type casting with non-primitive data types in Java?

Yes, you can use type casting with non-primitive data types, especially when dealing with objects and inheritance. This is common in object-oriented programming to specify that an object of a superclass should be treated as one of its subclasses, and vice versa.

Is explicit casting safe?

Explicit casting can be safe if you're sure of the data types you're working with. However, it comes with risks, especially with downcasting, as it can lead to runtime errors if the object isn't actually an instance of the subclass. Always check your types before casting.

Conclusion

In this article, we've learned about type casting in Java, a powerful feature that allows you to convert data from one type to another. We've saw how to write the syntax for type casting, differentiated between widening and narrowing type casting, and discussed explicit casting, both upcasting and downcasting. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Nested Class in Java
Next article
Java Program to Find All Palindromic Sub-Strings of a String
Live masterclass