codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

8 / 65 topics
1Java Intro2Java Get Started3Java Syntax4Java Output5Java Comments6Java Variables7Java Data Types8Java Type Casting9Java Operators10Java Strings11Java Math12Java Booleans13Java If...Else14Java Switch15Java While Loop16Java For Loop17Java Break/Continue18Java Arrays
Tutorials/Java Programming/Java Type Casting
☕Java Programming

Java Type Casting

Updated 2026-05-12
15 min read

Java Type Casting

In the previous tutorial, we explored Java data types, which are fundamental building blocks for any Java program. Understanding these types is crucial, but it's equally important to know how to convert one type into another. This process is known as type casting. In this tutorial, we'll delve into two primary types of casting in Java: widening (implicit) and narrowing (explicit).

Introduction

Type casting allows you to convert a variable from one data type to another. It's essential for operations that require different data types or when interfacing with APIs that expect specific types. Understanding how to perform these conversions correctly is vital for writing robust and error-free Java programs.

Why Type Casting Matters

  1. Data Conversion: Sometimes, you need to convert a variable from one type to another to perform certain operations.
  2. Interfacing with APIs: Many APIs expect data in specific types, so casting is necessary when working with them.
  3. Avoiding Errors: Improper casting can lead to runtime errors or unexpected behavior.

In this tutorial, we'll cover both widening and narrowing casting, providing examples and best practices for each.

Widening Casting (Implicit)

Widening casting occurs when you convert a smaller data type into a larger one. This conversion is done automatically by the Java compiler because there's no risk of losing data during the conversion.

Common Data Type Hierarchy

Here's a common hierarchy of numeric data types in Java:

Smaller TypesLarger Types
byteshort
shortint
intlong
floatdouble

When converting from a smaller type to a larger one, the compiler automatically handles the conversion.

Example of Widening Casting

Java
1// File: WideningCasting.java
2public class WideningCasting {
3 public static void main(String[] args) {
4 int intValue = 10;
5 double doubleValue = intValue; // Automatic widening casting
6
7 System.out.println("Int value: " + intValue);
8 System.out.println("Double value: " + doubleValue);
9 };
10}
Output
Int value: 10
Double value: 10.0

In this example, the int variable intValue is automatically cast to a double when assigned to doubleValue. The output shows that the integer value 10 is converted to 10.0, demonstrating the implicit widening casting.

Best Practices for Widening Casting

  • Automatic Conversion: Since this type of casting is automatic, you don't need to explicitly write any conversion code.
  • No Data Loss: Be aware that while there's no data loss in widening casting, precision might be affected when converting to floating-point types (e.g., int to double).

Narrowing Casting (Explicit)

Narrowing casting occurs when you convert a larger data type into a smaller one. This conversion is not automatic because it can lead to data loss or truncation if the value exceeds the range of the target type.

Example of Narrowing Casting

Java
1// File: NarrowingCasting.java
2public class NarrowingCasting {
3 public static void main(String[] args) {
4 double doubleValue = 10.9;
5 int intValue = (int) doubleValue; // Explicit narrowing casting
6
7 System.out.println("Double value: " + doubleValue);
8 System.out.println("Int value: " + intValue);
9 }
10}
Output
Double value: 10.9
Int value: 10

In this example, the double variable doubleValue is explicitly cast to an int using (int). The fractional part .9 is truncated, resulting in the integer value 10.

Common Mistakes with Narrowing Casting

  • Data Loss: Always be cautious of potential data loss when narrowing casting. For example, converting a large long to an int can result in incorrect values if the number exceeds the range of int.
  • Explicit Syntax: Remember that explicit casting requires parentheses around the target type.

Best Practices for Narrowing Casting

  • Check Range: Before performing narrowing casting, ensure that the value falls within the range of the target type to avoid unexpected results.
  • Use Conditional Statements: Implement checks using conditional statements if necessary to handle out-of-range values gracefully.

Practical Example: Temperature Conversion

Let's create a practical example where we convert temperatures from Celsius to Fahrenheit and vice versa. This will demonstrate both widening and narrowing casting in action.

Java
1// File: TemperatureConverter.java
2public class TemperatureConverter {
3 public static void main(String[] args) {
4 double celsius = 25.0;
5 double fahrenheit;
6
7 // Widening casting from int to double
8 fahrenheit = (celsius * 9/5) + 32;
9 System.out.println("Celsius: " + celsius + " -> Fahrenheit: " + fahrenheit);
10
11 // Narrowing casting from double to int
12 int roundedFahrenheit = (int) fahrenheit;
13 System.out.println("Rounded Fahrenheit: " + roundedFahrenheit);
14 }
15}
Output
Celsius: 25.0 -> Fahrenheit: 77.0
Rounded Fahrenheit: 77

In this example:

  • We first perform a widening casting from double to double when calculating the Fahrenheit value.
  • Then, we use narrowing casting to convert the double Fahrenheit value to an int, rounding down the decimal part.

Summary

ConceptDescription
Widening CastingAutomatic conversion from a smaller type to a larger one without data loss.
Narrowing CastingExplicit conversion from a larger type to a smaller one with potential data loss.
  • Widening Casting: Use it when converting to a larger type where no data is lost.
  • Narrowing Casting: Be cautious and use it only when necessary, ensuring that the value fits within the target type's range.

What's Next?

Now that you have a solid understanding of type casting in Java, the next step is to explore Java Operators. Operators are essential for performing operations on variables and data types. They allow you to manipulate values, perform calculations, and make decisions in your programs. In the next tutorial, we'll cover various operators, including arithmetic, relational, logical, and assignment operators, along with examples of how to use them effectively.

Stay tuned!


PreviousJava Data TypesNext Java Operators

Recommended Gear

Java Data TypesJava Operators