22
DecType Casting in Java: Implicit vs Explicit with Examples
Typecasting in Java
Type Casting in Java, commonly known as type conversion, is an important technique that allows us to transform one data type into another. It is useful when we need to execute operations on several data types or when we wish to save a value from one data type in another. Type casting in Java is the process of transforming variables between multiple data types, which is necessary for flexible programming.
In the Java tutorial, we will look into several aspects of Typecasting in Java, including types of typecasting, implicit type casting & explicit type casting, handling data loss and precision issues, typecasting between object references, and many more.
Accelerate your development career with our comprehensive Java Full Stack Developer Training—join now!
What is Typecasting in Java?
Typecasting in Java is the process of transforming the value of one data type (such as an integer [int], float, or double) to another. The compiler conducts the automated conversion while the programmer does the manual conversion. To utilize a variable in a certain fashion in automatic conversion, we must explicitly instruct the Java compiler to transform the variable from one data type to another.
Syntax
<datatype> variableName = (<datatype>) value;
Read More |
Data Types in Java - Primitive and Non-Primitive Data Types |
Types of variables in Java with examples: Local, Instance & Static |
Types of Typecasting
There are two types of typecasting in Java that are following below:
- Widening Type Casting (Implicit Typecasting)
- Narrowing Type Casting (Explicit Typecasting)
What is Implicit Typecasting?
Implicit Typecasting is also known as widening typecasting. Widening typecasting is the technique of converting a lower data type into a higher data type. This approach is computerized and safe, as there is no chance of data loss. This form of conversion and casting in Java occurs when:
- The source data type should be less than the destination data type.
- The two data types should be appropriate.
Syntax
larger_data_type variable_name = smaller_data_type_variable;
Example: Transforming int data type to double data type
class Main {
public static void main(String[] args) {
// create int data type variable
int num = 5;
System.out.println("The integer number is: " + num);
// changing into double data type
double data = num;
System.out.println("The double number is: " + data);
}
}
Output
The integer number is : 5
The double number is : 5.0
Explanation
- We have taken a variable num that stores the value 5 and printed it to the console.
- After that, we converted the num variable to the double data type and stored it as a data variable, and the result 5.0 was printed in the console.
Limitations of Implicit Typecasting
There are several limitations for Implicit type casting that are followed below:
1. Unpredictable Behavior
- Loss of precision when converting complex types (e.g., floats to integers).
- Unintended conversions can lead to bugs (e.g., string concatenation instead of numeric addition).
2. Reduced Code Clarity
- Harder to read and debug due to conversions happening behind the scenes.
- Over-reliance on implicit casting can lead to less robust code.
3. Performance Overhead
- It may impose a minor performance cost owing to runtime type determination.
4. Compatibility Issues
- Cross-language portability problems due to different types of constraint rules.
- Changes in language versions may alter implicit casting behavior.
What is Explicit Typecasting?
Explicit Typecasting is also known as narrowing typecasting. Narrowing type casting is the method of converting a bigger data type into a smaller data type. The narrowing type casting is risky because the lower data type's limited range of allowable values may result in data loss. The cast operator aids in explicit casting.
Syntax
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
Example: transforming double data type to int data type
class Main {
public static void main(String[] args) {
// creating double type variable
double num = 8.99;
System.out.println("The double value is: " + num);
// transform into int type
int data = (int)num;
System.out.println("The integer value is : " + data);
}
}
Output
The double value: 8.99
The integer value: 8
Explanation
In the above example,
- We have declared a double variable name num, stored the value 8.99, and printed it.
- After that, we declare an int variable named data, and int data = (int)num; will convert the double value to int value and the output 8 pint in the console.
Handling Data loss and Precision Issues In Explicit Typecasting
Handling data loss and precision concerns in explicit typecasting necessitates careful conversion management to maintain correctness and avoid unexpected outcomes. Here are a few strategies:
1. Check for Range Compatibility
Before casting, make sure that the target type can handle the range of values from the source type to avoid overflow or underflow.
2. Round or Truncate as Needed
When casting from a floating-point type to an integer, decide whether to round, floor, or truncate the value explicitly to control how precision loss is handled.
3. Use Larger Data Types When Necessary
If you anticipate precision loss, consider using a larger data type that can hold the value without losing significant digits (e.g., using double instead of float).
4. Use Explicit Conversion Functions
Instead of relying on casting, use explicit conversion functions or methods provided by the language that handle precision and data loss more gracefully, such as Math.round() in Java, for more precise control.
5. Validate Data Post-Conversion
After casting, validate the converted data to ensure it meets the expected range and precision. This can involve checking for significant digits or comparing against the original value.
Example: Transforming int data type to String data type
class Main {
public static void main(String[] args) {
// creating int type variable
int num = 8;
System.out.println("The integer value is: " + num);
// converts int to string type
String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}
Output
The integer value is: 8
The string value is: 8
Explanation
- We have created a int data type variable and store 8 value in num variable.
- After that we declare String data type variable and String data = String.valueOf(num); convert the int value to string data value.
Read More |
while Loop in Java |
for Loop in Java: Its Types and Examples |
What is String in Java - Java String Methods & Type (Examples) |
Type Casting Between Object Reference
Type casting between object references in Java involves converting an object of one type into another. This process is essential when dealing with inheritance and interfaces in Java. Type casting between object references can be categorized into two types:
- Upcasting
- Downcasting
Read More |
Single Inheritance in Java |
Multiple Inheritance in Java |
Hybrid Inheritance in Java |
1. Upcasting
Converting a subclass reference to a superclass reference. This type of casting is always safe and implicit (automatic). Upcasting is generally used when you wish to treat a subclass object as an instance of its superclass, which is usually done to take advantage of polymorphism.
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = dog; // Upcasting: Dog to Animal
animal.makeSound();
}
}
Output
Bark
Explanation
- In the main method, Creates a new Dog object and assign it to the variable dog.
- Animal animal = dog; This is upcasting. The Dog object is assigned to an Animal reference variable animal. This is possible because Dog is a subclass of Animal.
- Calls the makeSound() method on the animal object. and print the result.
2. Downcasting
It is the method of converting a superclass reference back to a subclass reference. This type of casting must be done explicitly and can be unsafe, potentially leading to a ClassCastException at runtime. Downcasting is used when you need to access subclass-specific methods or fields that are not available in the superclass.
Example
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting
dog.bark();
}
}
Output
Bark
Explanation
In this above example, we have created a parent class Animal with a single method makeSound() and a child class Dog with its own method bark(), which inherits from Animal.
- In the main method, created a Dog object and stored it as an animal variable referenced by the Animal known as upcasting.
- Dog dog = (Dog) animal; is downcasting. We are casting the Animal reference animal back to a Dog reference dog.
Note: To avoid 'ClassCastException', it's a good practice to check the type before downcasting using the 'instanceof' operator. |
Example
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
if (animal instanceof Dog) {
Dog dog = (Dog) animal; // Safe downcasting
dog.bark();
} else {
System.out.println("Not a Dog");
}
}
}
Output
Bark
Explanation
In the above example, we have created a parent class Animal with a single method makeSound() and a child class Dog with its own method bark(), which inherits from Animal.
- In the main method, created a Dog object and stored it as an animal variable referenced by the Animal known as upcasting.
- In if statement, we use instanceof operator to check if the referenced by animal is actually an instance of Dog.
- Inside the if statement, Dog dog = (Dog) animal; is downcasting. We are casting the Animal reference animal back to a Dog reference dog.
Read More |
Top 50 Java MCQ Questions |
Java Multithreading Interview Questions and Answers 2024 |
Top 50+ Java 8 Interview Questions & Answers 2024 |
Summary
In the above article, we have thoroughly explored the topic of typecasting in Java. I hope this article will definitely help you clear your doubts regarding typecasting and enhance your programming skills. Understanding both implicit and explicit typecasting is essential for smoothly managing type conversions. If you are a beginner in Java programming, enroll in our Full Stack Java Developer Course to grab the comprehensive step-by-step guide to Java.