Forums Register Login

Why This????

+Pie Number of slices to send: Send
public class Test{
int i=9;
int j=2;
Test(){
System.out.println(i/j);//Why 9/2 is printing 4 instead of 4.5
}
public static void main(String arg[]){
Test t = new Test();
}
}

Why 9/2 is printing 4 instead of 4.5
Pls Explain....
+Pie Number of slices to send: Send
Hi Mathews,


Why 9/2 is printing 4 instead of 4.5


Because the result of the division of two "int"s is an "int" (and not a "float" or "double"). This is explained in the Java Language Specification.
If you would like to get the result of "4.5" then try this:

Good Luck,
Avi.
+Pie Number of slices to send: Send
Hi ,
byte-->short-->int-->float-->double this sequence is "promotion".
("widening")
byte<--short<--int<--float<--double this sequence is "casting".
("narrowing")
If the result isn't the same as your expection, or having an error ("possible loss of precision") after compiling, you can check this first.
Hope this helps.
Legend has it that if you rub the right tiny ad, a genie comes out.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 958 times.
Similar Threads
Question on switch
why?
a switch problem
Interface Q
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:01:40.