In this article you will learn about Java type conversion and casting with appropriate examples. Converting a value from one type to another type (data type) is known as type conversion.
In Java, type casting and type conversion are used to convert one data type to another.
Type casting is done by placing the target data type in parentheses before the value being converted. For example:
1 2 3 | int i = (int) 5.6; |
Type conversion is done using predefined methods in Java. For example:
To convert a string to an integer:
1 2 3 4 | String str = "123"; int i = Integer.parseInt(str); |
To convert an integer to a string:
1 2 3 4 | int i = 123; String str = Integer.toString(i); |
To convert a float to a string:
1 2 3 4 | float f = 123.45f; String str = Float.toString(f); |
Note that type casting can result in loss of data if the target data type cannot hold the value being converted, while type conversion can result in a runtime exception if the string being parsed cannot be converted to the target data type.
Implicit Conversion or Coercion
Implicit conversion, also known as coercion, is a type of type conversion in Java where the compiler automatically converts one data type to another without explicit instruction from the programmer. This conversion is performed when a value of one type is used in an operation or expression that requires a different type.
For example, in Java, when a smaller data type (such as an int
) is used in an expression with a larger data type (such as a long
), the smaller type is automatically converted to the larger type:
1 2 3 4 | int i = 42; long l = i; // Implicit conversion from int to long |
In general, Java will perform implicit conversions between numeric data types when the target type is able to accurately represent the value of the source type.
It is important to keep in mind that implicit conversions can sometimes lead to unexpected results or loss of precision, so it’s a good practice to perform explicit type conversions whenever necessary.
Explicit Conversion or Casting
Explicit conversion, also known as casting, is a type of type conversion in Java where the programmer explicitly specifies the target data type of the conversion. This is done by placing the target data type in parentheses before the value being converted.
For example, consider the following code:
1 2 3 4 | double d = 5.6; int i = (int) d; // Explicit conversion from double to int |
In this example, the value of the double
variable d
is explicitly cast to an int
by placing int
in parentheses before d
. This results in the fractional part of the double
value being truncated, and the resulting int
value being assigned to the variable i
.
It’s important to be careful when performing explicit conversions, as the target data type may not be able to accurately represent the value being converted, resulting in loss of information or precision. In such cases, it may be necessary to perform additional calculations or checks to ensure that the converted value is valid and accurate.
fraction component will be lost.
Type promotion in expressions
Type promotion in expressions refers to the process in Java where the compiler automatically promotes smaller data types to larger data types when they are used in operations or expressions with data types of a larger size. This is done to avoid loss of information or precision during the evaluation of the expression.
For example, consider the following code:
1 2 3 4 | short s = 42; int i = s + 10; // Type promotion of short to int |
In this example, the short
variable s
is used in an expression with an int
value (10), and the short
value is automatically promoted to an int
to avoid any loss of information or precision during the evaluation of the expression. The result of the expression is an int
value, which is assigned to the variable i
.
In general, Java follows a set of rules for type promotion in expressions, where smaller data types (such as byte
, short
, and char
) are promoted to larger data types (such as int
, long
, float
, and double
) when necessary. If the expression involves multiple data types of different sizes, the compiler will perform type promotion on all the operands to ensure that the expression can be evaluated without loss of information or precision.
In addition to assignment statements, there is another place where type conversion can occur. It is in expressions. An expression is a collection of variables, values, operators and method calls which evaluate to a single value.
Type promotion rules of Java for expressions are listed below:
- All char, short and byte values are automatically promoted to int type.
- If at least one operand in an expression is a long type, then the entire expression will be promoted to long.
- If at least one operand in an expression is a float type, then the entire expression will be promoted to float.
- If at least one operand in an expression is a double type, then the entire expression will be promoted to double.
To understand the above type promotion rules let’s consider the following example of expression evaluation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Sample { public static void main(String[] args) { int i = 1000000; char c = 'z'; short s = 200; byte b = 120; float f = 3.45f; double d = 1.6789; double result = (f * b) + (i / c)–(d * s); System.out.println("Result = " + result); } } |
Output of the above program is: Result = 8274.22
This Java code defines a class named Sample
that contains a main
method, which is the entry point for a Java program. The main
method performs the following operations:
- Declares and initializes six variables:
i
,c
,s
,b
,f
, andd
.i
is anint
with the value1000000
.c
is achar
with the value'z'
.s
is ashort
with the value200
.b
is abyte
with the value120
.f
is afloat
with the value3.45f
.d
is adouble
with the value1.6789
.
- Calculates the value of the expression
(f * b) + (i / c) - (d * s)
and assigns the result to thedouble
variableresult
. - Prints the value of
result
to the console using theprintln
method. The string"Result = "
is concatenated withresult
to form the final output.
So the results of the sub expressions are float, int and double. Since one of them is a double, the result of the entire expression is promoted to a double.
Take your time to comment on this article.