jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Why This???? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why This????" Watch "Why This????" New topic

Why This????

Mathews P Srampikal
Ranch Hand

Joined: Nov 26, 2002
Posts: 211
public class Test{
int i=9;
int j=2;
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....

Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1141

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,
WY Hsiao

Joined: Oct 31, 2003
Posts: 4
Hi ,
byte-->short-->int-->float-->double this sequence is "promotion".
byte<--short<--int<--float<--double this sequence is "casting".
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: Why This????
It's not a secret anymore!