Java Type Casting
Java Type Casting
In Java, type casting is a process of converting one data type into another. It can be categorized into two types:
-
Widening Type Casting (Implicit Type Casting)
- Automatically performed by Java when converting a smaller data type to a larger data type.
- No data loss occurs during this conversion.
- Example:
byte -> short -> int -> long -> float -> double
-
Narrowing Type Casting (Explicit Type Casting)
- Manually performed by the programmer when converting a larger data type into a smaller data type.
- Data loss can occur if the value exceeds the range of the target type.
- Example:
double -> float -> long -> int -> short -> byte
Widening Type Casting Example
public class TypeCastingExample {
public static void main(String[] args) {
// Example of Widening (Implicit) Type Casting
int num = 100;
double doubleNum = num; // Automatically converts int to double
System.out.println("Integer value: " + num);
System.out.println("Double value after widening: " + doubleNum);
}
}
Explanation:
- The
int
value100
is automatically converted todouble
. - No explicit cast operator
(type)
is required.
Narrowing Type Casting Example
public class TypeCastingExample {
public static void main(String[] args) {
// Example of Narrowing (Explicit) Type Casting
double doubleNum = 100.99;
int intNum = (int) doubleNum; // Manually casting double to int
System.out.println("Double value: " + doubleNum);
System.out.println("Integer value after narrowing: " + intNum);
}
}
Explanation:
- The
double
value100.99
is explicitly cast toint
using(int)
. - The fractional part
.99
is truncated, resulting in data loss.
Type Casting Between Non-Primitive Types
Java also allows type casting for objects when:
- Two classes are related by inheritance.
- Explicit casting is required for downcasting (parent to child type).
Upcasting (Widening, Implicit):
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class UpcastingExample {
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = dog; // Upcasting (implicit)
animal.sound();
// animal.bark(); // Not accessible because of upcasting
}
}
Downcasting (Narrowing, Explicit):
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class DowncastingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting (explicit)
dog.sound();
dog.bark(); // Accessible after downcasting
}
}
Casting Between Wrapper Classes
Wrapper classes like Integer
, Double
, etc., also support type casting through auto-boxing and unboxing.
Auto-boxing Example (Primitive to Wrapper):
public class AutoBoxingExample {
public static void main(String[] args) {
int num = 50;
Integer wrappedNum = num; // Auto-boxing
System.out.println("Primitive int: " + num);
System.out.println("Wrapped Integer: " + wrappedNum);
}
}
Unboxing Example (Wrapper to Primitive):
public class UnboxingExample {
public static void main(String[] args) {
Integer wrappedNum = 50;
int num = wrappedNum; // Unboxing
System.out.println("Wrapped Integer: " + wrappedNum);
System.out.println("Primitive int after unboxing: " + num);
}
}
Best Practices
- Always ensure the target data type can handle the source data to prevent loss of precision or runtime errors.
- Use instanceof to verify object types before downcasting:
if (animal instanceof Dog) { Dog dog = (Dog) animal; }
- Avoid unnecessary casts as they may lead to performance overhead.
Advanced Concepts in Type Casting
1. Casting Between Numeric Data Types
When working with arithmetic operations or assigning values, type casting is often required between numeric types (e.g., int
, float
, double
, etc.).
Example: Arithmetic Operations
public class NumericCasting {
public static void main(String[] args) {
int a = 5;
double b = 2.0;
// Implicit casting in arithmetic
double result = a + b; // 'a' is automatically cast to double
System.out.println("Result: " + result);
// Explicit casting
int explicitResult = (int) (a + b); // Result of addition is explicitly cast to int
System.out.println("Explicit Result: " + explicitResult);
}
}
2. Casting Between Characters and Numbers
Characters in Java (char
) can be cast to and from integer types because they are internally stored as Unicode values.
Example: Character to Integer
public class CharToInt {
public static void main(String[] args) {
char ch = 'A';
int unicodeValue = ch; // Implicit casting
System.out.println("Unicode value of '" + ch + "': " + unicodeValue);
// Explicit casting back to char
int num = 66;
char newChar = (char) num;
System.out.println("Character for Unicode value 66: " + newChar);
}
}
Explanation:
'A'
has a Unicode value of 65.- Casting
int
tochar
retrieves the corresponding character.
3. Casting Arrays
You cannot directly cast between arrays of different types, but you can cast between arrays of objects if they share a parent-child relationship.
Example: Casting Object Arrays
public class ArrayCasting {
public static void main(String[] args) {
Object[] objArray = new String[3];
objArray[0] = "Java";
objArray[1] = "Type Casting";
objArray[2] = "Example";
for (Object obj : objArray) {
System.out.println((String) obj); // Downcasting each element to String
}
}
}
4. Casting with Interfaces
If a class implements an interface, the object can be cast to that interface type.
Example: Casting to Interface
interface Animal {
void sound();
}
class Cat implements Animal {
public void sound() {
System.out.println("Meow");
}
}
public class InterfaceCasting {
public static void main(String[] args) {
Animal animal = new Cat(); // Upcasting to interface
animal.sound();
// Downcasting back to specific type
if (animal instanceof Cat) {
Cat cat = (Cat) animal;
System.out.println("Downcast successful!");
}
}
}
Common Errors in Type Casting
1. ClassCastException
Occurs when you try to cast an object to an incompatible type.
Example:
public class CastingError {
public static void main(String[] args) {
Object obj = new String("Hello");
Integer num = (Integer) obj; // Will throw ClassCastException
}
}
2. Loss of Data
When narrowing numeric types, there is a risk of data loss due to precision truncation.
Example:
public class DataLossExample {
public static void main(String[] args) {
double pi = 3.14159;
int truncatedPi = (int) pi; // Fractional part is lost
System.out.println("Truncated Pi: " + truncatedPi);
}
}
3. Incompatible Primitive Types
You cannot directly cast between incompatible primitive types like boolean
and int
.
Invalid Example:
public class InvalidCasting {
public static void main(String[] args) {
boolean flag = true;
// int num = (int) flag; // Compile-time error
}
}
Casting in Real-world Scenarios
1. Parsing Strings to Numbers
Often used when taking user input or working with string-based data.
public class ParseExample {
public static void main(String[] args) {
String str = "123";
int number = Integer.parseInt(str); // String to int
System.out.println("Parsed number: " + number);
String decimalStr = "45.67";
double decimal = Double.parseDouble(decimalStr); // String to double
System.out.println("Parsed decimal: " + decimal);
}
}
2. Object Serialization
Type casting is used when reading objects from a serialized stream.
import java.io.*;
public class ObjectCasting {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject("Hello, Java!");
oos.close();
FileInputStream fis = new FileInputStream("data.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject(); // Read object from file
String message = (String) obj; // Downcast to String
System.out.println("Read from file: " + message);
ois.close();
}
}
Practice Problems
-
Write a program to:
- Perform widening and narrowing casting between
int
anddouble
. - Print the values before and after casting.
- Perform widening and narrowing casting between
-
Create an
Animal
class and two subclassesCat
andDog
.
Demonstrate upcasting and downcasting. -
Parse a string array containing numeric strings (e.g.,
["10", "20", "30"]
) into an integer array and calculate their sum.
Comments
Post a Comment