Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Casting
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Casting is the action of converting between two different data types such as converting an int to a double and vice versa. Examine the code below for examples of casting.
CastingExample.java
package exlcode;
public class CastingExample {
// this converts 15.23 into an integer
public static int exampleVariableOne = (int) 15.23;
public static double exampleVariableTwo = exampleVariableOne;
public static void main(String[] args) {
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}
We just converted the double value 15.23 into an integer, which left only the whole number and the decimal places to be cut off. There is no rounding, it just ignores the numbers after the decimal point during casting. When you convert an int to a double, a decimal point will be added to match with the structure of a double. For example, double varOne = (double) 15; assigns 15.0 to varOne.
Even though it is possible to convert an int to a double without casting, it is best practice to always use casting for precision and thorough logic. Also, be careful with the loss of precision when converting data types. i.e. losing decimal points is losing precision.