Type Casting
Explore the concept of type casting in Java, focusing on converting between int and double primitive types. Understand implicit casting during operations, explicit casting using syntax, and how overflow affects value ranges. This lesson helps you develop practical skills for handling type conversions correctly in your code.
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
inttype variables results in anotherinttype variable with the decimal dropped:7/2 = 3 - The division of two
doubletype variables results in anotherdoubletype 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).
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 ...