The moose likes Beginning Java and the fly likes Why does 8 equal 8.5? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does 8 equal 8.5?" Watch "Why does 8 equal 8.5?" New topic

Why does 8 equal 8.5?

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Part of the program I'm writing looks like this:

int counter
// lines that set the value of counter to 17
if ((counter/2)==((int)(counter/2))){
return true;
return false;

I get a return of true. It seems to me that counter/2 should equal 8.5 and that (int) (counter/2) should equal 8 and that 8.5 and 8 are not equal. Why do I get a return value of true?
This is the way I find out if an integer is divisible by two. I've been programming in BASIC all my life and recently tried out java. Is there a better way in java to find out if an integer is divisible by another integer?
Max Habibi
town drunk
( and author)

Joined: Jun 27, 2002
Posts: 4118

a quick question: is 8.5 an int?

Java Regular Expressions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38107
There are Five arithmetic operators in Basic, or at least there were when I last programmed Basic back in the 1970s [ ], namely +-*/ and **, but you could use ^ instead of **.
There are Five arithmetic operators in Java, which are +-*/ and %.

% returns the remainder when you divide one number by another. Try that.

Basic is [or at least, was] an un-typed language; if you have x = 3, then it just takes x as a number, without checking whether you want it to be a "real" number, ie one with a decimal point in, or an integer. Java is strongly typed; you have to tell the compiler what format every variable takes; if it is an integer, you have to say so.
And as for 8.5, the rules of integer arithmetic were the same in the 1970s as they are nowadays, and one of them is that integer division returns an integer result, not a fractional result. Try it out: using integer arithmetic work out 7 / 2 * 2, then 7 * 2 / 2.

And there is no need for the if statements. All you have to do is write
It will work out true and false for you.

Don't get me started about those stupid light bulbs.
subject: Why does 8 equal 8.5?
Similar Threads
JavaRanch style: Avoiding use of break /return in the middle of a method
Equals Method problem
Calendar Class
prime number problem