Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Cast of double to int after mathematical operation

Thomas Markl
Ranch Hand
Posts: 192
In this example a divide an double through an int. According to numeric
promotion result of this operation is an double which I explicitly cast to
int to assign it to int y.

public class Test60 {
public static void main(String ar[]) {
double i=4;
int j=3;
int y;
y = (int) i/j; //Numeric promotion: math operation involving int
//and double results in a double. Therefore cast
//of double to int to assing result to int y!
System.out.println("y = "+y); //prints y = 1;
}
}

In this example I divide two double and according result is double of course.
But why doesn’t y = (int) i/j cast double to int? When I say (int) i/j then I
cast to int why is it still double?
public class Test60 {
public static void main(String ar[]) {
double i=4;
// int j=3;
double j = 3;
int y;
y = (int) i/j; //Numeric promotion: math operation involving int
//and double results in a double. Therefore cast
//of double to int to assing result to int y!
System.out.println("y = "+y); //prints y = 1;
}
}

C:\Java\EigeneJavaProgramme>javac Test60.java
Test60.java:7: possible loss of precision
found : double
required: int
y = (int) i/j; //Numeric promotion: math operation involving int
^
1 error

Ron Newman
Ranch Hand
Posts: 1056
(int)i/j is the same as ((int)i)/j . You are casting i, not i/j, to int.
Since j is still a double, ((int)i)/j is a double and can't be assigned to an int without casting.
[ November 01, 2002: Message edited by: Ron Newman ]

Ron Newman
Ranch Hand
Posts: 1056
By the way, this should be posted to "Java in General (beginner)" , not "JavaRanch". Could someone please move it?

Carl Trusiak
Sheriff
Posts: 3341
Correct, Beginner is where this belongs. See it there

Thomas Markl
Ranch Hand
Posts: 192
Thanks Ron,
now I know my mistake. I corrected it and it was ok:
y = (int) (i/j); //ok now.

Bert Bates
author
Sheriff
Posts: 8898
5
The cert exam doesn't test your knowledge of precedence very heavily, but for some reason it will test your knowledge of casting precedence... should this go to cert?

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?