Java Type Casting
What Is Type Casting in Java?
Type casting in Java refers to converting a variable from one data type to another. This can happen automatically (by the compiler) or manually (by the programmer). It’s also called type conversion.
Common examples:
int to double
double to int
short to long
Types of Type Casting in Java
Type | Description | Performed By |
Widening Casting | Converting smaller type to larger type | Compiler |
Narrowing Casting | Converting larger type to smaller type | Programmer |
Widening Type Casting (Implicit Conversion)
Widening casting happens automatically when a smaller data type is assigned to a larger one. No special syntax is needed.
Conversion Hierarchy
byte → short → char → int → long → float → double
Example: Implicit Conversion
public class WideningDemo {
public static void main(String[] args) {
int num1 = 5004;
double num2 = 2.5;
// int is automatically converted to double
double result = num1 + num2;
System.out.println("Sum: " + result);
}
}Sum: 5006.5
Type Conversion Error
If you try to assign a larger type to a smaller type without explicit casting, the compiler throws an error.
Example: Invalid Implicit Conversion
public class ConversionErrorDemo {
public static void main(String[] args) {
int num1 = 5004;
double num2 = 2.5;
// Error: double cannot be assigned to int without casting
int result = num1 + num2;
System.out.println("Sum: " + result);
}
}Narrowing Type Casting (Explicit Conversion)
Narrowing casting is done manually using the cast operator. It’s required when converting a larger type to a smaller one.
Syntax
targetType variable = (targetType) sourceVariable;
Example: Explicit Conversion
public class NarrowingDemo {
public static void main(String[] args) {
int num = 5004;
// Convert int to double
double doubleValue = (double) num;
System.out.println("Converted to double: " + doubleValue);
// Convert double back to int
int intValue = (int) doubleValue;
System.out.println("Converted back to int: " + intValue);
}
}Converted to double: 5004.0 Converted back to int: 5004
Summary
Conversion Type | Direction | Automatic | Risk of Data Loss |
Widening | Small → Large | Yes | No |
Narrowing | Large → Small | No | Yes |