Type Casting
Type casting means converting a value from one data type to another. Java allows this so a value stored in one type (say, a double) can be used where another type (say, an int) is expected, following certain rules.
1. What is Type Casting?
Type casting means converting a value from one data type to another. Java allows this so a value stored in one type (say, a double) can be used where another type (say, an int) is expected, following certain rules.
2. Why is it used?
Sometimes your program stores data in one type but needs it in another for a calculation or a method call. Type casting lets you bridge that gap safely, either automatically or with explicit instructions from you.
3. Real-Life Example
Think of pouring juice from a large jug into a small glass. Some juice fits perfectly (like converting a small type to a bigger type automatically), but if you pour too much into a smaller glass, some juice spills out — similar to losing precision when converting a bigger type into a smaller one.
4. Syntax
java// Implicit (automatic) casting - smaller to bigger type double d = 100; // int to double automatically // Explicit casting - bigger to smaller type, needs manual instruction int i = (int) 9.8;
5. Example Program
javapublic class CastingDemo { public static void main(String[] args) { double price = 99.99; int roundedPrice = (int) price; // explicit casting System.out.println("Original: " + price + ", Casted: " + roundedPrice); } }
Output:
Original: 99.99, Casted: 996. Key Points to Remember
- Implicit casting happens automatically when there's no risk of data loss.
- Explicit casting requires
(type)and may lose data (like decimal points). - Casting between unrelated types (like
Stringtointdirectly) is not allowed this way — special methods are needed instead.