devxlogo

The Fraction Gotcha In Java

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist