Java Type Conversion – Time to upskill your Programming
There are some cases while coding when different types of constants and variables mix in an expression. To perform operations on them, we need to convert them into the same type.
Here comes the concept of Type Conversion or Type Casting in Java, which is used to convert one predefined value to the other. In this Java article, we will discuss everything you need to know about type casting in Java. We will cover its types with examples.
What is Type Conversion in Java?
Type Conversion or Type Casting is the process of converting a variable of one predefined type into another.
If these data types are compatible with each other, the compiler automatically converts them and if they are not compatible, then the programmer needs to typecast them explicitly. Don’t get confused with the word compatible, we are going to cover this term in our article.
Types of Type Conversion in Java
Java facilitates type conversion in two forms:
- Implicit (Automatic) Type Conversion
- Explicit Type Conversion
Implicit Type Conversion
Implicit Type Conversion or Automatic type conversion is a process of automatic conversion of one data type to another by the compiler, without involving the programmer.
This process is also called Widening Conversion because the compiler converts the value of narrower (smaller size) data type into a value of a broader (larger size) data type without loss of information. The implicit data type conversion is possible only when:
- The two data types are compatible with each other.
- There is a need to convert a smaller or narrower data type to the larger type size.
The above image shows the conversions that Java allows. For example, the compiler automatically converts byte to short because the byte is smaller ( 8 bits ) or narrower than short ( 16 bits ).
byte ——— is convertible to ————-> short, int, long, float, or double
Short ——— is convertible to ————-> int, long, float, or double
char ——— is convertible to ————-> int, long, float, or double
int ——— is convertible to ————-> long, float, or double
long ——— is convertible to ————-> float or double
float ——— is convertible to ————-> double
Code to understand Automatic Type Conversion in Java:
package com.techvidvan.typeconversion; public class ImplicitTypeConversion { public static void main(String[] args) { int intVariable = 25; long longVariable = intVariable; float floatVariable = longVariable; double doubleVariable = floatVariable; System.out.println("Integer value is: " +intVariable); System.out.println("Long value is: " +longVariable); System.out.println("Float value is: " +floatVariable); System.out.println("Double value is: " +doubleVariable); } }
Output:
Long value is: 25
Float value is: 25.0
Double value is: 25.0
Explicit Type Conversion
The Explicit Type Conversion is a process of explicitly converting a type to a specific type. We also call it Narrowing Conversion. The typecasting is done manually by the programmer, and not by the compiler.
We need to do explicit or narrowing type conversion when the value of a broader (higher size) data type needs to be converted to a value of a narrower (lower size) data type. For example, double data type explicitly converted into int type.
Syntax of explicit type conversion in Java:
The following is the syntax of typecasting in Java
(type) expression;
Where type is a valid data type to which the conversion is to be done. For example, if we want to make sure that the expression (x / y + 5) evaluates to type float, we will write it as,
(float)(x / y +5);
If we try to convert the smaller data types to larger data types without typecasting, then there will be a compilation error:
package com.techvidvan.typeconversion; public class Test { public static void main(String[] argv) { int intVariable = 10; long longVariable = 7878; intVariable = longVariable; } }
Output:
Type mismatch: cannot convert from long to intat project1/com.techvidvan.typeconversion.Test.main(Test.java:8)
The correct code is:
package com.techvidvan.typeconversion; public class Test { public static void main(String[] argv) { int intVariable = 10; long longVariable = 7878; //Type Casting to int intVariable = (int) longVariable; System.out.println(intVariable); } }
Output:
Code to understand Explicit Type Conversion in Java:
package com.techvidvan.typeconversion; public class ExplicitTypeConversion { public static void main(String[] args) { double doubleVariable = 135.78; //explicit type casting long longVariable = (long)doubleVariable; //explicit type casting int intVariable = (int)longVariable; System.out.println("Double value: "+doubleVariable); System.out.println("Long value: "+longVariable); System.out.println("Integer value: "+intVariable); char charVariable = 'A'; //explicit type casting int intVariable1 = (int)charVariable; System.out.println("\nInteger value of " +charVariable + " is " +intVariable1); //explicit type casting long longVariable1 = (long)intVariable1; System.out.println("Long value: "+longVariable1); } }
Output:
Long value: 135
Integer value: 135Integer value of A is 65
Long value: 65
Assignment Compatibility
As we know that, we can assign a value of an integer type to a value of the same type or wider type without typecasting. In this case, the compiler automatically widens the value to the appropriate type.
A value of any integer type can be cast to a value of any other integer type. However, Integer types can not be cast to a boolean value, nor can the boolean type be cast to an integer type value.
The following table shows whether an assignment from a particular integer type to another integer type can be directly done or it requires a typecast.
Conversion of Primitive types
When performing type conversion with primitive types, the following situations may arise:
1. Assignment Operation
Assignment conversion occurs when we assign a variable of one type to another type. We can only implement the widening or implicit type conversion through an assignment operation. For example,
int number1 ; byte number2 ; number1 = number2 ; //number2 automatically converts to int
2. Integer Promotion
When evaluating the integer expressions, Java automatically recognizes the need for type conversion and performs it accordingly by carrying out Type Promotion. Consider the following Java example:
int num = 5 double sum = 30; double average = sum / num; //num also converts to double
3. Conversion during a method call
This type of conversion takes place when we call a method and the passed argument of a datatype to the method expects a different data type.
Suppose the argument passed to the method is of int type and the method requires a long data type then the int automatically converts into long at the time of calling the method.
For example,
float floatVariable = 4.56f; double doubleVariable = Math.sin(floatVariable); //method sin() expects double and hence floatVariable converts to double
Conversion and Casting of Reference Types
We know that class, interface, and an array include reference types. There can’t be an arithmetic promotion with reference type conversion since object references cannot be arithmetic operands.
Rules for Reference Type Conversion
- We can convert class type to a class type or to an interface type. Converting to a class type requires that the new type must be the parent class of the old type. And, converting to an interface type requires that the old class must implement the interface.
- We can convert an interface type only to an interface type or to the Object. If we convert to the interface type, then the new type must be a parent interface of the old type.
- We can convert an array to the Cloneable or Serializable interface, to the Object class, or to an array.
Code to understand the conversion of reference types:
package com.techvidvan.typeconversion; public class ReferenceTypeConversion { class Shape { } class Square extends Shape { } public static void main(String[] args) { Shape s1 = new Shape(); Square s2 = new Square(); s1 = s2; //allowed s2 = s1; //not allowed } }
Output:
Reference Type Conversion during Method Invocation
The Conversion of a reference type is also possible when we pass a reference type to a method that accepts an argument of a different type. We can convert to a superclass but not to a subclass. For Example,
package com.techvidvan.typeconversion; public class ReferenceTypeConversion { class Shape { } class Square extends Shape { } public static void myMethod(Shape s) { } public static void main(String[] args) { Square s1 = new Square(); myMethod(s1); } }
Summary
We call the process of changing values from one data type to another as Typecasting or Type Conversion. Using Type Casting, you can convert larger or wider types to the smaller or narrower types.
And, if the conversion needs to be done from smaller or narrower types to the larger or wider types, then the compiler automatically converts them using implicit type conversion. We can also typecast the reference variables.
In this article, we discussed the implicit and explicit type conversions. Implicit Conversion is also called automatic or Widening conversion and Explicit Type conversion is also called Narrowing Conversion. I hope this article will help you sharpen your concepts in type conversion in Java.
Thank you for reading our article. If you have any doubts related to Java Type Conversion, do let us know by dropping a comment below.
Keep Learning 🙂