Explicit Type Casting Examples Java Primitives and Class Objects
This tutorial explains what is explicit type casting in Java and how to do explicit casting in primitive data types such as int, char etc., and referenced data types such as class.
Explicit Type Casting in Java
Whenever a programmers does type casting explicitly, it is called as explicit type casting.
And explicit type casting is mandatory while converting from higher data type to a lower data type (in case of primitive data types). To know the lower and higher data types, the following representation might be useful for you.
byte, short, char, int, long, float, double lower <-------------------------------------> higher
In case of casting referenced data types (class is a referenced data type) by doing explicit type casting you can convert one class type to another class type. Converting a sub class type in to a super class type is called “Generalization” or “Widening” or “Up-casting“. Similarly you can convert a super class type in to a sub class type and this is called as “Specialization” or “Narrowing” or “Down-casting“.
Let’s see in more detail with examples how to do explicit type casting in primitive data types and referenced data types in the below sections.
Explicit Type Casting in Primitive Data Types
Before you get in to explicit type casting in primitive data types, you should know that you can convert lower data type in to a higher data type (Implicit Casting) and this is called as “Widening“. The below examples are for widening.
Example 1: ---------- char c = 'A'; int n = (int)c; //n contains 65 which is the ASCII value of 'A' Example 2: ---------- int x = 2500; float price = (float)x; // price contains 2500.0
Note, widening is safe to do because you won’t be facing any data loss or accuracy issues. That is the reason why even if programmer does not use casting operator, JVM compiler does the casting operation itself internally for you and hence this is also called as “Implicit Casting“.
Therefore, the following statements will work perfectly without using casting operator as shown in the example without any compilation issues.
1) char c = 'A'; int n = c; //n contains 65 which is the ASCII value of 'A' 2) int x = 2500; float price = x; // price contains 2500.0
What is Implicit Casting ?
Implicit casting can be used to convert lower data type to higher data type. JVM compiler automatically does casting internally and it is called as implicit casting.
Explicit Casting in Primitive Data Types
When you convert higher data type in to lower data type, it is called as “Narrowing” or “Explicit Casting“. The below examples are for narrowing.
Example 1: ---------- int num = 65; char c = (char)num; //c contains 'A' Example 2: ---------- double d = 24.567; int num = (int)d; //num stores 24
If you see in the above examples, when you convert higher data type (double) to lower data type (int), the value in “d” was “24.567” and when it is converted to int, the value has become “12” which is stored in “num“. Here we lost some digits.
Therefore, narrowing is not safe in case of primitive data types and hence Java compiler forces the programmer to use casting operator and the programmer must cast the data type. So narrowing is also called as explicit casting.
Explicit Casting – Referenced Data Types or Class Objects
Widening in referenced data types
A class is a referenced data type. In case of widening in referenced data types, we convert sub class object type to super class type by using super class reference to refer to sub class object as shown in the example below. Here, the sub class object type is converted into super class type sup= (Super)new Sub(); .
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method2(){ System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ //widening Super sup; //sup -> super class reference sup= (Super)new Sub(); //sup refer to sub class object sup.method1(); } }
Output
In Super
Note, in the above case we will be able to call method1() of super class, but we won’t be able to call the method2() of sub class. If you try to call method2() it would result in compile time error.
Therefore, in case of widening in referenced data types, the programmer will be able to access all the methods of super class, but not the sub class methods. We can say programmer has access to only 50% of the functionalities.
Let’s try one more thing to execute methods of sub class. Let’s override the super class methods in the sub class as shown in the example below, then it is possible to access sub class methods but not the super class methods. In either cases programmer will get only 50% functionality.
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method1(){ //override the super class method System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ //widening Super sup; //sup -> super class reference sup= (Super)new Sub(); //sup refer to sub class object sup.method1(); } }
Output
In Sub
Narrowing in referenced data types
In case of narrowing in referenced data types, we convert super class type to sub class type. Let’s try taking sub class reference to refer to super class object as shown in the example below and see what happens.
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method2(){ System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ //narrowing Sub sub; //sub -> sub class reference sub= (Sub)new Super(); //sub refer to super class object sub.method1(); } }
Output
Exception in thread "main" java.lang.ClassCastException: Super cannot be cast to Sub
Therefore, in narrowing if you use super class object we cannot access any methods of super class or even sub class. Try sub.method2(), that will also result in same error. So programmer will get 0% functionality if super class object is used while narrowing.
The solution to the above problem is try to create an object to sub class while narrowing instead of creating an object to super class as shown in the following example.
class Super { void method1(){ System.out.println("In Super"); } } class Sub extends Super { void method2(){ System.out.println("In Sub"); } } class Cast { public static void main(String args[]){ //narrowing Super sup; //sup -> super class reference //create an object to sub class sup = new Sub(); //sup -> super class reference refer to sub class object Sub sub = (Sub)sup; // narrowing - convert super class reference //access super class and sub class methods - 100% functionality access sub.method1(); sub.method2(); } }
Output
In Super In Sub
It is evident that if an object to sub class is created, then it is possible to access all the methods of super class and sub class. Then while narrowing using sub class object will enable 100% functionality accessibility.
Note, this is the reason why in inheritance we always create an object to sub class, but not to super class.
Also See:
- How to declare and initialize arrays in Java Programming ?
- Java 8 : Find union and intersection of two Lists (ArrayLists)
- Manipulate Java 8 Stream data sources or objects?
- Copy contents of a List to another List in Java
- Replace element in ArrayList at specific index
- Convert Integer List to int array
- Convert comma separated String to List
- Find intersection of two Sets