aspose file tools*
The moose likes Beginning Java and the fly likes Double question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Double question" Watch "Double question" New topic
Author

Double question

Ah Sam
Greenhorn

Joined: Sep 26, 2007
Posts: 3
Dear Guru,

I have a question here.
I have define a double which looks like this:

double a = 2/3;
double b = 2/3d;

When I System.out.println, I got this result
a = 0.0
b = 0.6666666666666666

Any guru there can answer me why?
Thanks in advance.
bart zagers
Ranch Hand

Joined: Feb 05, 2003
Posts: 234
I'm sorry, but not a guru

double d = 2 / 3

Both 2 and 3 are integers, therefore an integer division is done which gives zero as the integer result. This result is then converted to a zero double.

double d = 2 / 3d

Here 3 is a double, therefore the 2 is converted to a double and a double division is done, which gives 0.666 as result that is assigned to the double d

(therefore for example
int i = 2 / 3 would work fine, and
int i = 2 / 3d not)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14150
    
  18

"myahsam", please check your private messages. You can see them by clicking My Private Messages.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ah Sam
Greenhorn

Joined: Sep 26, 2007
Posts: 3
Thanks for your clear explanation!
Appreciate it.
Ah Sam
Greenhorn

Joined: Sep 26, 2007
Posts: 3
Thanks for your clear explanation!
Appreciate it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double question