Type Casting
Let's learn how a variable of one type can be casted to a variable of another type.
We'll cover the following...
While writing programs in Java, you will often need to change an int
type variable to a double
type variable or vice versa. There are also some operations that implicitly interconvert types. For example, the division of an int
type variable with a double
type variable.
Let’s look at this case first.
Implicit type casting
In the basic cases, i.e., the division of similar type variables, the data type of the result remains preserved. This means that:
- The division of two
int
type variables results in anotherint
type variable with the decimal dropped:7/2 = 3
- The division of two
double
type variables results in anotherdouble
type variable:7.0/2.0 = 3.5
However, if the variables have different types, i.e., one variable is int
type and the other is double
type, the resulting variable is of double
type, and the decimal part is retained. The lower data type int
(having smaller size) is converted into the higher data type double
(having larger size).
class ImplicitTypeCasting{public static void main(String args[]){double var1 = 2; // double type variableint var2 = 7; // int type variableSystem.out.println(var2/var1); // int type divided by double typeSystem.out.println(var1/var2); // double type divided by int type}}
We declare a double
type variable (var1
) and an int
type variable (var2
). At line 8, we divide var2
by var1
. Notice that we get a double
value as a result instead of an int
value. The same goes for the next line, where we divide var1
by var2
.
Explicit type casting
We also have operations that explicitly change the type of variables. To convert an int
type variable to a double
type, we have the (double)
operation. Similarly, to convert a double
type variable to an int
type, just add (int)
before it and assign it to an int
type variable. During the integer casting with the (int)
method, the decimal part of the double
type variable is dropped. The higher data types, e.g. double
, (having larger size) are converted into lower data types, e.g. int
, (having smaller size).
class ExplicitTypeCasting{public static void main(String args[]){// casting int to doubleint intVar = 3; // int type variableSystem.out.println(intVar); // prints 3double castedDoubleVar = (double) intVar; // casting int to a double variableSystem.out.println(castedDoubleVar); // prints 3.0// casting double to intdouble doubleVar = 3.14; // double type variableSystem.out.println(doubleVar); // prints 3.14int castedIntVar = (int) doubleVar; // casting double to an int variable, decimal droppedSystem.out.println(castedIntVar); // prints 3}}
At line 6, we create an int
variable: intVar
. Then, at line 9, we explicitly type cast the variable to a double
type variable: castedDoubleVar
. We use the (double)
method for this.
Similarly, at line 13, we create a double
variable: doubleVar
. Then, at line 16, we explicitly type cast the variable ...