• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cast of double to int after mathematical operation

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, this should be posted to "Java in General (beginner)" , not "JavaRanch". Could someone please move it?
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct, Beginner is where this belongs. See it there
 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 8900
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic