go to previous page   go to home page   go to next page hear noise

Do you expect that a modern electronic calculator will give you the same answer as Java for the expression  (31.5 - 12)/4.1 ?

Answer:

Yes. The meaning of operators and parentheses is about the same in electronic calculators and in Java. But Java does integer and floating point math, and sometimes this can make a difference.


Weird Integer Arithmetic

The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division. The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.

There is a difference between what Java will do and what a calculator will do. A calculator will do floating point arithmetic for the expression:

7/4

A calculator will show this as 1.75. Java will regard this as integer arithmetic and give you:

7/4 = 1

because 4 goes into 7 just once. The result is not rounded up to 2. The remainder after division, 3, is simply dropped.

A handy way to think about integer division is to think about forming groups of pebbles. Say that you had twelve pebbles and wished to arrange them into groups of five. You can form two groups of five pebbles (with two pebbles left over).

12/5 = 2

Integer operations and floating point operations are both very common in programs. It is imporant to be clear about them. (Advanced Placement Computer Science students are expected to know this subject well.)



Expression ResultExpression Result
12 3 12 6
12 7 11 2
11.0 5.0 1 2
1.0 2.0 2.0 4.0

QUESTION 6:

What is the result of evaluating the following expression:

199/50