← Back to Chapters

Java Type Casting

? Java Type Casting

? Quick Overview

Type casting in Java is the process of converting one data type into another. It is commonly used when working with different numeric types or when narrowing or widening values.

? Key Concepts

  • Automatic (Widening) Casting
  • Manual (Narrowing) Casting
  • Primitive data type conversion
  • Risk of data loss in narrowing

? Syntax / Theory

Java supports two main types of type casting:

  • Widening Casting: Smaller type to larger type (automatic)
  • Narrowing Casting: Larger type to smaller type (manual)

? Code Example(s)

? View Code Example
// Widening casting example
int number = 10;
double result = number;
System.out.println(result);
? View Code Example
// Narrowing casting example
double price = 99.99;
int roundedPrice = (int) price;
System.out.println(roundedPrice);

? Live Output / Explanation

Output Explanation

The first example converts an int into a double automatically. The second example converts a double into an int manually, which removes the decimal part.

✅ Tips & Best Practices

  • Prefer widening casting as it is safe
  • Be careful with narrowing casting due to data loss
  • Use explicit casting only when required

? Try It Yourself

  • Convert a long value into an int
  • Cast a char to an int and observe the ASCII value