Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Sep 1, 1999

The Fraction Gotcha In Java

In Java The expression x/y (x and y are both integers) will represent an integer operation that would result in an integer. So, the result of 4/5 would be 0. This will happen even if you assign the result of the operation to a double. So,

 
 double d = 4/5; 

will still be 0. This is because 4/5 is evaluated first, and because it is an integer operation, the result is evaluated to be integer 0, now assigning it to double is the same as casting integer zero into a double, which will give you, well, ZERO.

If you need the floating point result of a division you should use floating point numbers. So, to get 0.8, which is the result of dividing 4 by 5, you can do 4.0/5 or 4/5.0 or 4.0/5.0.

Note that, in Java, a literal number containing a decimal point is a double, not a float. If you want it to be a mere float, you can put an "f" after it as in 4.0f.

Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date