Weird Integer Arithmetic

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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 number 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.

QUESTION 6:

What is the result of evaluating the following expression:

199/50