1. Widening or Automatic Type Conversion
Automatic or implicit type conversion is done by the compiler internally. Converting a lower data type into a higher one is known as widening. If two variables involved in an operation are of the same data type, the result is also similar. If variables of different but compatible data types are involved, then implicit conversion is automatic.
Implicit conversion follows the given order:
For example, char variables can be typecasted to int, float can be typecasted to double and so on.
public class Main
{
public static void main(String[] args)
{
char ch = 'a';
int a = ch;
System.out.println(a);
long a = 20;
float b = 24.62f;
double x = a*b;
System.out.println(x);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
97
472.4000244140625
The char type is automatically converted to int. Variables a and b, which are of long and float data type, respectively, are multiplied to give a value stored in a double type variable. So, long and double are implicitly cast to double.
Note that if we try to typecast a float variable to a double without adding a float literal, it will result in an error stating lossy conversion. This is because variables of double data type have more precision than float. The error is a warning from the compiler indicating reduced precision.
2. Narrowing or Explicit Conversion
Narrowing or Explicit conversion involves casting a higher data type into a lower one. This type of conversion is not done automatically, and the desired data type needs to be explicitly mentioned within ( ). Data types need not be compatible with each other for explicit typecasting.
Explicit conversion uses the following order:
public class Main
{
public static void main(String[] args)
{
int a = 102;
char ch = (int) a;
System.out.println(ch);
double x = 328.288006786;
long y = (long) x/20;
System.out.println(x);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
f
16
In the above example, an int variable is explicitly converted to char, which is of lower order. Similarly, result y, by default, will be of double type but has been converted to long data type. Hence, y stores the integer answer of the division operation.
Examples of Type Casting in Java
Type casting in Java is a way of converting a variable from one data type to another. In Java, there are two types of casting:
Widening Casting (Implicit): This occurs when data from a smaller data type is converted into a larger data type automatically. For example, converting an int to a long.
Narrowing Casting (Explicit): This is done manually by the programmer. It converts a larger data type to a smaller size type. For example, converting a double to an int.
Examples
Widening Casting Example:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
You can also try this code with Online Java Compiler
Run CodeExplanation: Here, myInt is an integer. When it's assigned to myDouble, Java automatically converts the int to a double. This is a widening cast because a double is larger than an int.
Narrowing Casting Example:
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
You can also try this code with Online Java Compiler
Run CodeExplanation: In this, myDouble is a double with a value of 9.78. To assign it to myInt, which is an integer, we need to perform a narrowing cast. This is done by prefixing the value with (int). The fractional part (.78) is truncated, and myInt becomes 9.
Type Promotion in Expressions
In Java, Type Promotion is the process of converting a smaller data type into a larger data type and is done automatically by the Java compiler itself when an expression is evaluated.
Type promotion helps in preventing errors as it ensures that all expressions are evaluated using the same data type.
Let's see the rules of type promotion:
- Byte, short and char are upgraded to int
- one operand is long then the whole expression is promoted to long
- one operand is float then the whole expression is promoted to float
- If any operands are double, the result is double
Here is an example of type promotion in Java:
public class HelloWorld{
public static void main(String []args){
// Byte promoted to int
byte i = 10;
int x = i + 5;
System.out.println("byte converted int -> "+x);
// Short promoted to int
short short_num = 15;
int Big = short_num + 115;
System.out.println("short converted int -> "+Big);
// int promoted to double
int num = 5;
double Big_num = num + 15.5;
System.out.println("int converted double -> "+Big_num);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
byte converted int -> 15
short converted int -> 130
int converted double -> 20.5
Explicit Type Casting in Expressions
Explicit Type Casting is the process of converting the data type of a variable to another data type manually by the programmer. It is done using the cast operator which is pair of parentheses containing the data type to which the value is being converted. like (data_type)
It is used whenever the compiler fails to convert the data type automatically to another data type and prevents the compile time error.
Here is an example of Explicit Type Casting in Java:
public class HelloWorld{
public static void main(String []args){
// Cast double to float
double num = 10.51;
float res = (float) num;
System.out.println("double casted to float -> "+res);
// Cast char to int
char ch = 'z';
int number = (int) ch;
System.out.println("char casted to int -> "+number);
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
double casted to float -> 10.51
char casted to int -> 122
Frequently Asked Questions
What is the condition for type conversion in Java?
The condition for type conversion in Java is that both of the datatypes should be compatible with each other. For example, we can convert the byte to int but not byte to float data type or string as it is not a valid conversion.
Which type conversion is not accepted in Java?
Type conversion that is not accepted in Java is when there is a conversion between two incompatible datatypes. For example, converting int to a string data type is not accepted.
How many forms of type conversion are there in Java?
There are basically two types of conversion one is the implicit type where the data type is converted automatically by the compiler and the other one is explicit data type conversion where in we manually convert the data type to another.
Why do we need type casting in Java?
We need typecasting in Java to ensure the compatibility between the data types of the operands. Type casting in Java helps in the prevention of errors and makes the program to run as expected.
What is difference between type casting and type conversion?
Type casting and type conversion both involve changing data types, but type casting is explicit and programmer-controlled, while type conversion can be implicit and automatic by the programming language.
Conclusion
Type conversions are essential when dealing with multiple variables of different data types. Implicit and Explicit conversions play an important role in obtaining the desired output. This blog discusses primitive and non-primitive data types in Java. It mainly focuses on type conversion in Java with examples in detail.
Related Links
Java Tokens
Java Verify
Multiple Inheritance in Java
Data types and identifiers in Java
Check out the official Coding Ninjas Blog site and visit our Library for more.