Java tutorials > Core Java Fundamentals > Basics and Syntax > What is type casting and its types?
What is type casting and its types?
Type casting in Java is the process of converting a variable from one data type to another. This is crucial when you need to perform operations that require specific data types or when you want to store a value of one type in a variable of a different type. Java supports both widening (implicit) and narrowing (explicit) type casting.
Understanding Type Casting
Type casting involves converting a value from one data type to another. Java is a strongly-typed language, meaning each variable must have a declared type. Sometimes, you need to treat a variable as if it were a different type to perform certain operations.
Widening Casting (Implicit Conversion)
Widening casting happens automatically when converting a smaller data type to a larger data type. No explicit casting operator is required. Since you are going to a 'bigger container', there is no information loss. It's also known as implicit conversion or automatic type conversion. Here's the order of widening conversions: byte -> short -> char -> int -> long -> float -> double
Widening Casting Example
In this example, the integer myInt
is automatically converted to a double myDouble
. No explicit casting operator is needed.
public class WideningCasting {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic widening casting: int to double
System.out.println("myInt: " + myInt); // Outputs 9
System.out.println("myDouble: " + myDouble); // Outputs 9.0
}
}
Narrowing Casting (Explicit Conversion)
Narrowing casting requires explicit conversion using the cast operator (data_type)
. It occurs when converting a larger data type to a smaller one. This conversion may lead to loss of data as you are going to a 'smaller container'. Here's the order of narrowing conversions: double -> float -> long -> int -> char -> short -> byte
Narrowing Casting Example
In this example, the double myDouble
is explicitly converted to an integer myInt
. Note that the decimal part is truncated, leading to a potential loss of data.
public class NarrowingCasting {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit narrowing casting: double to int
System.out.println("myDouble: " + myDouble); // Outputs 9.78
System.out.println("myInt: " + myInt); // Outputs 9 (decimal part is truncated)
}
}
Concepts Behind the Snippet
The key concept is understanding the size and range of different data types. Widening casting is safe because it moves to a data type with a larger range. Narrowing casting, however, involves moving to a smaller range, which may result in data loss.
Real-Life Use Case
Consider reading sensor data as float and needing to store it as integers to minimize memory usage on an embedded system. You would perform narrowing casting (float to int), acknowledging potential data loss due to truncation. Another example is when interacting with libraries that use specific data types, you might need to cast your variables to match the expected input type.
Best Practices
Interview Tip
During interviews, be prepared to explain the difference between widening and narrowing casting, provide examples, and discuss the potential consequences of each. Also, mention autoboxing and unboxing as related concepts.
When to use them
Use widening casting when you need to perform operations involving different numeric types and don't want to lose precision. Use narrowing casting when you need to fit a value into a smaller data type and are willing to accept potential data loss.
Memory Footprint
Type casting itself doesn't directly change the memory footprint of a variable. The size of the variable is determined by its declared data type. However, narrowing casting can reduce memory usage if you're storing the result in a smaller data type (e.g., double to int).
Alternatives
Instead of narrowing casting with potential data loss, consider using methods like Math.round()
, Math.floor()
, or Math.ceil()
to round floating-point numbers to integers based on specific rounding rules. These methods allow for more controlled conversion than direct truncation.
Pros of Type Casting
Cons of Type Casting
ClassCastException
errors if you try to cast an object to an incompatible type.
FAQ
-
What happens if I try to cast an object to an incompatible type?
You will get aClassCastException
at runtime. -
Is it always safe to perform widening casting?
Yes, widening casting is generally safe because you are converting to a larger data type, so there is no loss of information. -
Why is narrowing casting considered unsafe?
Narrowing casting is unsafe because you are converting to a smaller data type, which can result in the loss of data or precision. -
What is the difference between primitive type casting and object type casting?
Primitive type casting involves converting between primitive data types (e.g., int to double), while object type casting involves converting between different classes or interfaces in an inheritance hierarchy. Object type casting requires the use of inheritance and polymorphism.