What is Type Casting
Type casting in java refers to converting one data type into others. There are two types, Implicit type casting and explicit type casting, in java. Type casting means we are casting the values from one data type to another.
Implicit Type Casting
Implicit type casting means casting is done by compiler, value conversion is automatically done by compiler. We are not supposed to do anything. Will go through below code to understand.
Converting small data type to larger data type is called implicit type casting also known as widening.
Type Casting in Java
Example: Suppose we have a small glass of 2 ML water capacity and another one with 20ML of capacity, here we can easily put water from 2 ML glass to 20 ML since the capacity of another glass is big. Similarly, in case of java we can convert int data type to double as the int is smaller and double can accept it.
Implicit Type Casting example
public class TypeCastingImplicitExample {
public static void main(String args[]) {
int smallGlassCap = 2;
double bigGlassCap = 20;
System.out.println( smallGlassCap + bigGlassCap);
}
}
In the above code what we are doing is that we have declared two variables smallGlassCap and bigGlassCap as int and double respectively, then we are performing the addition and printing it on the console. See below output.
22.0
Observe the output its 22.0, The .0 is what represents double number, that means compiler automatically converted the 2 which is integer to double this is what we call it as implicit type casting.
Explicit Type Casting
What is Explicit type casting, By default compiler does not allow the explicit type casting. In explicit type casting we manually need to type case, i.e. explicitly we need to define the type we are conversing.
Explicit type casting is the process of converting higher data type to lower data type also known as narrowing.
Type Casting in Java
In the same example of glass water capacity here we are going to put 20 ML water into 2ML, but that’s not possible right? Yes that’s correct it’s not possible to put 20 ML water into 2ML capacity glass therefore we need to do explicitly casting here. How? We will explicitly take only 2ML data and fit it. In Java’s technical words we are going to assign double value which is of 8 Bytes into int which is smaller data type as compared to double. Please see below code snippet.
Type casting in java example
public class TypeCastingImplicitExample {
public static void main(String args[]) {
int smallGlassCap = 2;
double bigGlassCap =20;
smallGlassCap = bigGlassCap;
System.out.println( smallGlassCap + bigGlassCap);
}
}
Output:
/TypeCastingImplicitExample.java:7: error: incompatible types: possible lossy conversion from double to int
smallGlassCap = bigGlassCap;
^
1 error
Explanation
In the above code example, we are converting double to int directly and running the program but it failed the reason is its unable to do the type conversion. To resolve it we need to explicitly tell compiler to type cast it. Please see below code snippet.
public class TypeCastingImplicitExample {
public static void main(String args[]) {
int smallGlassCap = 2;
double bigGlassCap =20;
smallGlassCap = (int) bigGlassCap;
}
}
The above code snippet compiles perfectly because we are explicitly defining the type to be cast here. (int) This is how we can do the explicit type casting using (TYPE_NAME).
Java Type Casting FAQ
Let’s see some of the Frequently asked questions on type casting in java
What are the types of casting in java:
Two types implicit and explicit
What happens if you cast incompatible types ?
It will give you compilation error or runtime error based on types.
What is explicit type casting?
It’s type casting that we need to explicitly define the type for which we are casting.
What is implicit type casting?
Its casting type, which is automatically done by java compiler.
What is the difference between type casting and type conversion ?
Type conversion is a process of converting value of one data type to another, and type casting is conversion of one variable data type to another.
What is difference between implicit and explicit type casting ??
The difference between implicit and explicit type casting is that implicit happens automatically without manual action from the programmer while explicit requires them to explicitly specify a data type to convert to. Implicit type casting should generally be used when you want to upgrade from a smaller data type to something bigger while explicit conversion of variables from one data type to another is best left for explicit conversion.
What Are Some Common issues or problems of Type Casting?
One of the major drawback of type casting is the risk of losing precision or accuracy when converting data types, for eg. converting from float to int and then back again can truncate decimal points, leading to loss of precision which is not a good use case for banking type of transactions. Another issue may occur when converting between data types with differing ranges (float to integer for instance).
Java Wrapper Classes
What’s a Wrapper class ?
A wrapper class is a special type of class which wraps the primitive data types as an Object. What it means is that, it wraps the primitive data types to object representation.
8 Wrapper classes in java
So Java provides these 8 wrapper classes for each of these primitive type boolean, byte,
short, char, int, long, float, double.
Why we need Wrapper classes ?
Whenever we need to use any of these primitive data types as objects, then to convert them we need to use wrapper classes. The wrapper class also includes methods to unwrap the object and give back the primitive data type.
package com.slb.thread;
import java.util.ArrayList;
public class WrapperClassTest {
public static void main(String[] args) {
//below is not allowed
ArrayList<int> listOfNumbers = new ArrayList<int>();
//below works fine because of Wrapper class Integer
ArrayList<Integer> listOfNumbersInt = new ArrayList<Integer>();
}
}
Conclusion
Type casting is one of the important concept in java programming that helps us/ you to convert between various data types and its values. By understanding its various types of drawbacks and issues we can understand what are the best ways to apply type casting within your code, type casting can increase efficiency and readability of programs. Hope with this blog it helped you understand the importance and usage of type casting in java. For any questions feel free to comment and will try to answer.
Learn Other Java 8 Tutorials here
Please refer the code here at SLB-GITHUB.