Imagine that you are coding in Java and you need to perform calculations with different types of numbers, for example, an int to a double. Or maybe you received user input as a string but need to convert it into an int for further processing. Type casting is how Java handles these conversions.
Type casting is part of a broader concept called type conversion in Java, which is the process of converting a value from one data type to another. Type conversion in Java can happen in two ways:
Developers use type casting in Java in day-to-day tasks to avoid common pitfalls like data loss or runtime errors.
In this guide, we will cover:
- Widening Type Casting
- Narrowing Type Casting
- How to convert a string to int in Java
Table of Contents:
By the end of this blog, you will have a better understanding of type casting in Java and even be able to apply it in your own projects using the practical Java type casting examples.
What is Type Casting in Java?
In Java, variables come in different types, like int, float, double, char, and String. Java is also a strongly typed language, which means the type of every variable must be known at compile time. That’s great for catching bugs early, but it also means you have to be a little more deliberate when switching between types. That’s where type casting comes into use.
Simply put, type casting in Java lets you change the “type” of a variable or object so that Java can process it in the way you intend.
For example:
- Converting an int to a double so that decimal calculations are possible.
- Converting a String to an int to perform arithmetic operations on user input.
- Converting a double to an int when you only need the whole number part.
Type casting is a core concept in Java because it ensures that your program handles data safely and efficiently. There are two types of type casting in Java, which we will discuss in the next section.
Widening Type Casting in Java (Implicit )
Widening, or Implicit type casting in Java, is when you convert a smaller data type into a larger one. Imagine that you are pouring water from a small cup into a bigger one; nothing spills, and the transition is smooth.
Hierarchy of Widening in Java
In Java, data types have a sort of built-in hierarchy based on size and precision. For primitives, the order generally looks like this:
byte → short → int → long → float → double
So if you assign an int to a long, or a float to a double, Java knows it’s a safe move. No data will be lost, and no cast is needed.
Example: int to double
Output:
Here, num is an int, which is smaller in size than double. Java automatically converts num to double because no data will be lost in the process. This is why we don’t need any special syntax; it’s called implicit casting.
Narrowing Type Casting in Java (Explicit )
Narrowing, also known as explicit type casting in Java, occurs when you convert a larger data type into a smaller one. Since the smaller type may not be able to hold all the information from the larger type, data loss is possible, and the conversion must be done manually by the programmer.
How to Perform Explicit Type Casting in Java
In Java, narrowing or explicit type casting is done using parentheses with the target data type:
int smallerType = (int) largerType;
Example: double to int
Output:
Here, num is a double, which has a larger size than int. Converting it to int may cause loss of the decimal part. Java requires us to explicitly specify the type using (int), which is explicit casting.
Type Casting Between Non-Primitive (Reference) Types
So far, we have looked at type casting between primitive types like int, double, and float. But what about when you’re working with objects? This is where reference type casting comes in.
In Java, all classes are part of a hierarchy. That means one class can be a subclass (child) or superclass (parent) of another. You can cast objects up or down this hierarchy depending on the situation.
Let’s break it down.
1. Upcasting (Implicit)
Upcasting means converting a subclass type into a superclass type. This is safe and automatic, and Java handles it for you without complaint.
class Animal {}
class Dog extends Animal {}
Dog dog = new Dog();
Animal pet = dog; // Upcasting: Dog → Animal
Here, dog is automatically treated as an Animal. This is useful when writing flexible, reusable code (like working with collections of animals instead of individual species).
2. Downcasting (Explicit)
Downcasting is the reverse; you’re trying to treat a parent object as a more specific child type. Since not all Animal objects are actually Dogs, Java makes you cast explicitly, and even then, it’s risky.
Animal pet = new Dog(); // Upcast
Dog buddy = (Dog) pet; // Downcast (safe because pet is actually a Dog)
If the object isn’t actually an instance of the target class, you’ll get a ClassCastException at runtime.
3. When Casting Goes Wrong
Let’s look at a case that compiles fine but crashes when you run it:
Animal pet = new Animal(); // Just a plain Animal
Dog buddy = (Dog) pet; // This will throw an error
Why? Because a pet isn’t really a Dog, so Java can’t magically turn it into one.
Java Type Conversion Between Strings and Primitives
In Java, it’s common to work with data as strings, especially when reading user input or processing text from files. Often, you’ll need to convert strings to numbers to perform arithmetic, or numbers to strings to display results. Java provides built-in methods for this conversion.
1. Converting int to String in Java
You can convert an integer (or any primitive type) to a string using the String.valueOf() method.
Example:
- num is an int variable holding the value 10.
- String.valueOf(num) converts the integer into a string representation “10”.
- This is useful when you want to concatenate numbers with text or store them in text-based formats.
Output:
2. Converting String to int in Java
To perform calculations on user input or data read from a file, you often need to convert a string to a numeric type. Use Integer.parseInt() for integers or Double.parseDouble() for decimal numbers.
Example:
Output:
- data is a string containing numeric characters “20”.
- Integer.parseInt(data) converts it to the integer 20.
- Now, num can be used in arithmetic operations like addition, subtraction, etc.
Type Casting in Java Quick Reference Table
|
Type of Casting |
Conversion Direction |
Automatic? |
Data Loss? |
| Widening (Implicit) |
Smaller → Larger |
Yes |
No |
| Narrowing (Explicit) |
Larger → Smaller |
No |
Possible |
| String → Primitive |
String → int/float/double |
No |
Possible (invalid input) |
| Primitive → String |
int/float/double → String |
Yes |
No |
Type Casting in Java Best Practices
| Best Practice |
Description |
| Widening Type Casting |
Use whenever possible; it’s safe and happens automatically. |
| Narrowing Type Casting |
Use carefully; always check for potential data loss. |
| String to Number Conversion |
Handle exceptions to prevent runtime errors (e.g., NumberFormatException). |
Conclusion
Type casting in Java is essential for safely converting between data types, whether primitives or objects. Understanding widening and narrowing conversions helps prevent data loss and runtime errors.
To dive deeper into Java and master more concepts, check out our Java Certification Program, where we dig deeper into more Java topics such as data types, type erasures, and even classes and objects.
FAQs – Java Type Casting
1. What is the difference between type conversion and type casting in Java
Type conversion is done automatically in Java. It happens when Java promotes a smaller data type into a larger one.
int num = 5;
double result = num; // implicit conversion
Type casting, on the other hand, is manual and requires explicit syntax when converting a larger data type into a smaller one, which can lead to data loss.
double score = 9.99;
int rounded = (int) score; // manual casting
2. What is ClassCastException in Java? When does it occur, and how can you avoid it?
ClassCastException in Java is a runtime error that occurs when you try to cast an object into a subclass to which it is not an instance of.
Animal animal = new Animal();
Dog dog = (Dog) animal; // Throws ClassCastException
Use the instanceof operator to avoid ClassCastException by checking the object type before casting
3. Can you cast between any two types in Java?
No, in Java, you can only cast between compatible types. For primitive types, casting works when there’s a valid widening or narrowing path (like int to float, or double to byte).
For object types, the classes must share an inheritance relationship; otherwise, Java won’t allow it, and you’ll get a compile-time error.
4. Does casting affect performance in Java?
For most cases, casting in Java does not affect performance. But, unnecessary or unsafe casting, especially between objects, can lead to runtime errors and difficulty in debugging. So, it is recommended that you keep casting meaningful and minimal.