Introduction
In Java, different data types occupy varying amounts of memory. Sometimes, you may need to convert one type to another.For example, from a double
to an int
, or from an int
to a double
.
This process is called type casting
. Casting allows us to explicitly control how values are converted between data types
Types Of Casting
There are two main types of casting in Java. They are: Widening Casting (Automatic / Implicit) and Narrowing Casting (Explicit / Manual)
Widening Casting(Automatic/Implicit)
This is used when you are casting a smaller data type to a larger data type. With this type, no data will be lost from the conversion. Example changing an int
to a double
. For example;
int myInt = 10;
double myDouble = myInt; // Automatic conversion
System.out.println(myDouble); // Output: 10.0
Narrowing Casting (Explicit / Manual)
This is used when you are changing a larger data type to a smaller data type. This is riskier because data loss is more probable here. An example is changing double
to int
.
double x = 9.997;
int nx = (int) x; // Explicit cast
System.out.println(nx); // Output: 9
Notice how 9.997 becomes 9. This is because the decimal part is discarded.
Casting and Rounding
What if you don’t want to just throw away the decimal part?
That’s where Math.round() comes in.
double x = 9.997;
int nx = (int) Math.round(x); // Round to nearest int
System.out.println(nx); // Output: 10
Note: Math.round() returns a long. That’s why we add (int) to cast it back to int.
Real-World Example
Imagine you’re building a program that compares floating-point numbers up to 3 decimal places:
double num1 = 25.586;
double num2 = 25.589;
int n1 = (int)(num1 * 1000); // Casting after scaling
int n2 = (int)(num2 * 1000);
if (n1 == n2) {
System.out.println("They are the same up to 3 decimal places");
} else {
System.out.println("They are different");
}
Top comments (0)