
Java Type Casting in Java
? Java Type Casting
Type casting in Java is the process of converting one data type into another. There are two types:
? 1. Widening Casting (Implicit Casting)
Also known as automatic type conversion.
Happens when converting a smaller type to a larger type size.
byte ? short ? int ? long ? float ? double
Example:
int num = 100;double d = num; // int is automatically cast to doubleSystem.out.println(d); // Output: 100.0
? 2. Narrowing Casting (Explicit Casting)
Must be done manually by the programmer.
Converts a larger type into a smaller size type.
Can lead to data loss.
Syntax:
dataType variableName = (dataType) value;
Example:
double d = 9.78;int i = (int) d; // Explicit casting: double to intSystem.out.println(i); // Output: 9 (decimal part is lost)
? Special Cases
a. Casting between char and int
char ch = 'A';int ascii = (int) ch; // Output: 65int num = 66;char letter = (char) num; // Output: 'B'
b. Casting Objects (Reference Type Casting)
There are two types:
Upcasting: Subclass ? Superclass (Implicit)
Downcasting: Superclass ? Subclass (Explicit)
Example:
class Animal { void sound() { System.out.println("Animal sound"); }}class Dog extends Animal { void sound() { System.out.println("Dog barks"); } void fetch() { System.out.println("Dog fetches"); }}Animal a = new Dog(); // Upcastinga.sound(); // Output: Dog barksDog d = (Dog) a; // Downcastingd.fetch(); // Output: Dog fetches
? Summary Table
Casting Type | From ? To | Requires Cast? | Risk of Data Loss |
---|---|---|---|
Widening | int ? double | No | No |
Narrowing | double ? int | Yes | Yes |
Object Upcast | Subclass ? Superclass | No | No |
Object Downcast | Superclass ? Subclass | Yes | Yes (if invalid) |
Let me know if you want a cheat sheet or exercises on this topic!