1. Type Casting Overview
In this tutorial, We'll learn what is Type Casting and how it works in Java.
Type casting is used to convert an object or variable of one type into another.
This is done in two ways.
A) Implicit conversion or type casting
B) Explicit conversion or type casting
1.1 Syntax
DataType variableName = (DataType) variableNameToConvert;The above syntax is to covert one type to another type by specifying the Data Type of Target.
2. Implicit Type Casting
This is also called as Automatic Type Conversion or Widening.
If we assign value of one variable type to another, two types may be compatible or not compatible to each other.
If compatible then conversion will be done automatically. This type of conversion is called Automatic Type Conversion.
DataType1 type_variable_name = another_type_variable_name
This implicit conversion is done in 2 scenario's.
1) If both types are compatible
2) If destination data type is bigger than source data type (Assigning smaller data type to bigger data type)
In java, Numeric primitive data types are converted automatically from smaller to bigger types.
But this is not applicable to the boolean and char types because these two are not compatible to each other.
2.1 Automatic conversion hierarchy
below is the valid conversion's flow in java.
byte --> short --> int --> long --> float --> double
2.2 Example on Primitive Types
Creating a int type variable. Next, assigned int to double without specifying any type casting. This looks working magically to the new java developers.
int number = 10; double d = number;
The above code does not give compile time error and works perfectly fine. Here, implicit casting has been applied by compiler. So, no issue in this case.
2.3 Example with Inheritance
We will look at another example using inheritance.Creating A class.
class A { public void sayHello() { System.out.println("hello developer"); } }
Creating class B which extends class A.
class B extends A{ public void sayBye() { System.out.println("Hope you come back to this site soon."); } }
Now, we are going to assign type B to type A as below.
A a = new B(); a.sayHello();
This works well, no doubt in that. Because assigning sub class object to the it's super class reference. All the code is tested against JDK 12.
If we assign type A to B then will get compile time error saying "cannot convert from A to B". The reason behind this is there is no relationship between class A and B.
B b = new A();
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from A to B
2.4 Example on Generics with Wrapper classes
Example demonstration with Wrapper classes using Generics concepts.
Below example, Creating ArrayList instance which accepts any Number implementation classes such as Integer, Double, Float, BigInteger etc.
Listnumbers = new ArrayList (); numbers.add(new Integer(100)); numbers.add(new Double(100)); numbers.add(new BigInteger("123.5"));
Added Integer, Double and BigInteger objects but did not get any error because compiler does implicit casting for us based on those classes relation with Number class.
3. Explicit Type Casting
This is also called as Narrowing which means reducing the scope of the source type.
In other words, Assigning bigger data type to smaller data type or which are not compatible to each other.
We will see example program on each case with legal and illegal examples.
3.1 Example on primitive types
We will now implement a program to assign float to byte. We will see what will happen and how to eliminate error if anything comes.
float f = 30.087f; byte b = f;
Output:
When we compile this code then will through compile time error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from float to byte
Because float type is getting assigned to byte which is having less capacity. There may be loss of precision of values.
For make above code to work, we should add explicit type casting from float to byte as below.
float f = 30.087f; byte b = (byte)f;
Print the byte b value.
30
Because of narrowing, it will loose precision of value.
3.2 Example on User defined classes without any relation (Inheritance)
Let us create two classes C and D as below.
class C { // some methods } class D { // some methods }Now assign class C type to class D type. There is not relationship between class C and D. So, We must do explicit casting.
C c = new C(); D d = (D)c;
But, still compiler can determine that there no relationship among them. So, Will get compile time error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from C to D
3.3 Loss of Precision
Float holds decimal points and double hold very big values as when compared to int. See the below example where casting to int type.
float f1 = 3.14f; double d1 = 1234567890123456789d; int i1 = (int)f1; System.out.println("i1 : "+i1); int i2 = (int) d1; System.out.println("i2 : "+i2);
Output:
i1 : 3 i2 : 2147483647
It losts the actual float and double values because int can not hold the decimals. double value is completely changed after casting to int.
So, narrowing casting is not recommended to use unless it significantly effects.
4. Conclusion
We've seen What is type casting in java and how it works in different cases.
Discussed types of casting such as automatic and explicit type casting. Showed exmaple programs using primitive types, Wrapper classes with Generics and Inheritance.
Narrowing casting feature can not hold the actual values if the source type is bigger than the destination type.
All example code snippets shown in this article are available over GitHub.
No comments:
Post a Comment
Please do not add any spam links in the comments section.