This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why This????  RSS feed

 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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....
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
WY Hsiao
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!