Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.



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