Type Casting
in Java
Master widening and narrowing conversions to safely transform data between Java's primitive types.
What is Type Casting?
Type casting is the process of converting a value from one data type to another. In Java, every variable has a declared type, and sometimes you need to store a value in a variable of a different type.
Java's Primitive Type Hierarchy
Why Does Casting Matter?
Java is a strongly typed language. The compiler will not let you silently lose data. Understanding casting helps you:
Widening Conversion (Implicit)
When you assign a smaller type to a larger type, Java automatically promotes the value. No cast syntax needed.
Narrowing Conversion (Explicit)
When you assign a larger type to a smaller type, you must write an explicit cast. Java truncates the value to fit.
The Cast Syntax
The general form of an explicit cast in Java uses parentheses around the target type, placed before the expression:
Widening vs Narrowing
| Widening | Narrowing | |
|---|---|---|
| Direction | Smaller → Larger | Larger → Smaller |
| Syntax needed? | No (implicit) | Yes (explicit cast) |
| Data loss? | None | Possible (truncation/overflow) |
| Compiler error? | No | Yes, if cast is missing |
| Example | int → double | double → int |
How to Apply Type Casting
Example 1: Integer Division Fix
Problem: You want the precise result of dividing two integers, but Java gives you an integer result.
Example 2: Storing a Calculation
Problem: A method returns a double, but you need to store it as an int for an array index.
Example 3: Mixed-Type Expressions
Problem: What happens when you mix types in an arithmetic expression?
Automatic Promotion Rules
char and int Casting
In Java, a char is a 16-bit unsigned integer representing a Unicode character. You can cast freely between char and int.
Common Mistakes
Summary Reference Table
| Scenario | Code | Result |
|---|---|---|
| int → double | Implicit | Safe, no loss |
| double → int | (int) val | Truncated |
| int / int | a / b | Integer division |
| Force double division | (double) a / b | Precise result |
| char → int | Implicit | Unicode value |
| int → char | (char) val | Character |
Question 1 of 5
What is the output of the following code?
double x = 7 / 2;
System.out.println(x);
Question 2 of 5
Which of the following requires an explicit cast in Java?
Question 3 of 5
What is the value of result after this code executes?
double result = (double) 7 / 2;
Question 4 of 5
What does (int) -3.7 evaluate to in Java?
Question 5 of 5
Given:
byte b = (byte) 130;
What is the value of b?