TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » .NET » VB.NET » Math Processing
Language: Java
Expertise: Beginner
Sep 2, 1999

### WEBINAR:On-Demand

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

 Submit a Tip Browse ".NET" Tips Browse All Tips
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