العوامل الحسابية وقسمة الأعداد الصحيحة
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
So far your programs have stored values in labeled boxes and printed them. This module is about operators: the symbols that combine values into new values. Think of a calculator with a few extra buttons. You already know what + and * do on paper, so this lesson is mostly about the places where Java's answer differs from what a calculator would show.
The biggest surprise is one line long: in Java, 7 / 2 is 3, not 3.5. This lesson explains why, shows the operator that gives you the leftover (%), and teaches the habits that stop this surprise from becoming a bug.
Why this matters: nearly every backend calculation uses these operators: totals, averages, pages in a result list, minutes and seconds, cents and dollars. A silently wrong division gives wrong numbers without any error message, and nobody notices until a customer does.
This lesson builds on BEG-009: you need variables, the int and double types, and the idea that a value has a fixed type. It also reuses printing with + between text and numbers from BEG-009.
Learning Objectives
By the end of this lesson you will be able to:
- Use the five arithmetic operators
+,-,*,/,%onintanddoublevalues. - Predict the result of integer division, including with negative numbers.
- Use
%to get a remainder and to test whether a number is even. - Turn an integer division into a decimal one by making an operand a
double. - Split a quantity such as minutes or cents into whole units and a remainder.
- Say what happens when you divide by zero for
intand fordouble.
Written Explanation
The five operators
An operator is a symbol that takes values (called operands) and produces a new value. The arithmetic operators are:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 |
% | remainder (also called modulo) | 7 % 2 | 1 |
An expression such as 7 + 2 is not a statement by itself. It is a piece of code that evaluates to a value, and you use that value: print it, store it in a variable, or feed it into a bigger expression.
Integer division drops the fraction
The type of the result depends on the types of the operands. When both operands are int, the result is an int. An int has no room for a fraction, so / throws the fractional part away. It does not round: it cuts toward zero.
| Expression | Result | Why |
|---|---|---|
7 / 2 | 3 | 3.5 loses its .5 |
9 / 10 | 0 | 0.9 loses its .9 |
-7 / 2 | -3 | -3.5 is cut toward zero, not down to -4 |
The Java Language Specification states this rule: integer division rounds toward zero. There is no warning and no error. The program simply gives you 3, and if you meant 3.5 you must notice it yourself.
Getting a decimal result
If at least one operand is a double, Java converts the other one to double too (the widening conversion from BEG-009) and divides with decimals:
System.out.println(7 / 2); // 3 (int / int)
System.out.println(7 / 2.0); // 3.5 (int / double)This is the fix for the most common division mistake: make one operand a double before the division happens. You can write the number as 2.0, or cast a variable: (double) total / count. Be careful about where you put the cast. The cast applies to the value right after it, so (double) (a / b) divides first as integers and only then converts the already-truncated result.
The remainder operator %
% gives what is left over after division. For int values, division and remainder are partners: 7 / 2 is 3 (how many whole 2s fit) and 7 % 2 is 1 (what remains). The specification guarantees the relationship (a / b) * b + (a % b) == a for integers.
Three facts to remember:
- The remainder is always smaller in size than the divisor.
x % 10is always between0and9whenxis not negative. - With a negative left operand, the remainder takes the sign of the left operand:
-7 % 2is-1. Keep non-negative numbers in your first exercises and treat negative remainders as a detail to look up when you need it. %also works ondouble:7.5 % 2is1.5.
The most common use is the even test. A whole number n is even when dividing by 2 leaves no remainder, so n % 2 == 0 is true for even n. (The == here asks a yes/no question; the next lesson covers it.)
Whole units and remainder together
/ and % together split a quantity into big units and what is left. With 135 minutes: 135 / 60 is 2 hours and 135 % 60 is 15 minutes. The same pattern splits cents into dollars and cents, items into full pages and a short last page, and seconds into minutes and seconds.
Dividing by zero
What happens depends on the type:
intdivision or remainder by zero throws an exception while the program runs (ArithmeticException: / by zero) and the program stops.doubledivision by zero follows the floating-point standard and gives a special value:1.0 / 0isInfinity, and0.0 / 0isNaN("not a number"). The program keeps running, which is easy to miss.
Overflow still applies
Arithmetic on int stays int. If a result does not fit, it wraps around silently, as you saw with Integer.MAX_VALUE + 1 in BEG-009. Multiplication of two large int values is the usual way to trigger it.
Examples
Example 1: every operator once (simple)
public class Arith {
public static void main(String[] args) {
System.out.println(7 + 2);
System.out.println(7 - 2);
System.out.println(7 * 2);
System.out.println(7 / 2);
System.out.println(7 % 2);
System.out.println(-7 / 2);
System.out.println(-7 % 2);
System.out.println(7 / 2.0);
System.out.println(7.5 % 2);
System.out.println(1.0 / 0);
System.out.println(0.0 / 0);
}
}Output (JDK 21):
9
5
14
3
1
-3
-1
3.5
1.5
Infinity
NaNRead the output line by line against the table above. Lines 4 and 6 show truncation toward zero, and the last two lines show that double division by zero does not stop the program.
Example 2: minutes, even numbers, and an average (practical)
public class Time {
public static void main(String[] args) {
int total = 135;
int hours = total / 60;
int minutes = total % 60;
System.out.println(hours + " h " + minutes + " min");
int n = 10;
System.out.println(n % 2 == 0);
System.out.println(7 + 8 / 2);
System.out.println((7 + 8) / 2);
System.out.println((7 + 8) / 2.0);
}
}2 h 15 min
true
11
7
7.5The first two outputs use / and % as a pair and the even test. The last three show that 7 + 8 / 2 is 11, not the average (division happens before addition, a rule explained in Lesson 4), and that the average of two integers needs a double on the dividing side: (7 + 8) / 2 loses the .5, (7 + 8) / 2.0 keeps it.
Example 3: pages and prices (realistic)
A backend API returns 95 results, 10 per page. How many pages? And how do you show a price held as whole cents?
public class Pages {
public static void main(String[] args) {
int items = 95;
int perPage = 10;
System.out.println("full pages: " + items / perPage);
System.out.println("left over: " + items % perPage);
System.out.println("pages needed: " + (items + perPage - 1) / perPage);
int cents = 1999;
System.out.println(cents / 100 + "." + cents % 100);
cents = 1905;
System.out.println(cents / 100 + "." + cents % 100);
}
}full pages: 9
left over: 5
pages needed: 10
19.99
19.5Two lessons are hiding here:
95 / 10is9full pages with5items left, so 10 pages are needed. The expression(items + perPage - 1) / perPageis a common way to round a division up using only integers: addingperPage - 1pushes any non-empty remainder over the next whole number.- The price code is wrong for 1905 cents. It printed
19.5instead of19.05, because1905 % 100is the number5and the leading zero is lost. Remainder gives you a number, not a formatted piece of text. Formatting numbers comes later in the course; for now, remember that the arithmetic can be right while the display is wrong.
Backend Insight
Backend systems are full of integer arithmetic done on purpose:
- Money in whole cents. BEG-009 warned against
doublefor money. Storing cents as anintorlongmakes+,-, and*exact, and/and%split cents into currency units. Division is where care is needed:1000 / 3cents is333, and the leftover cent has to go somewhere according to a business rule, not be silently lost. - Pagination. "Items per page" arithmetic (
/and%, or the round-up formula above) sits behind almost every list endpoint. - Spreading load. A simple way to pick one of N servers or buckets for an id is
id % N. - Time. Conversions between seconds, minutes, and hours are
/and%chains.
In each case, a wrong operand type produces plausible-looking wrong numbers rather than an error. That is why this module insists on predicting an answer before running code.
Common Mistakes
Mistake 1: Expecting 5 / 2 to be 2.5
- Incorrect:
double half = 5 / 2;stores2.0. The division happens as integers first, and only the result2is widened todouble. - Correct:
double half = 5 / 2.0;ordouble half = (double) 5 / 2;stores2.5.
Mistake 2: Casting too late
- Incorrect:
(double) (a / b). The division is already finished and truncated inside the parentheses. - Correct:
(double) a / b, ora / (double) b.
Mistake 3: Assuming % is a percentage
% is the remainder, not "percent". 50 % 8 is 2. For 8% of 50, multiply: 50 * 8 / 100.
Mistake 4: Trusting double division by zero
5.0 / 0 does not crash; it gives Infinity and the program carries on with a bad value. Check the divisor first when it can be zero.
Mistake 5: Forgetting that negative numbers truncate toward zero
-7 / 2 is -3, not -4. If you round "down" in your head you will be off by one.
Exercises
Try each exercise yourself, and write a prediction before you run anything.
Level A: Foundation
A1. Evaluate without running: 10 / 3, 10 % 3, 10 / 3.0, 3 / 10.
أظهر الحل A1
A1. 3, 1, 3.3333333333333335, 0. The third uses a double divisor, so it keeps decimals (the long tail is normal for double). The fourth is 0 because 0.3 loses its fraction.
A2. Which of these are true? (a) 8 % 2 == 0 (b) 9 % 2 == 0 (c) 25 % 5 == 0
أظهر الحل A2
A2. (a) true, (b) false, (c) true.
A3. What is the result type of 4 * 2.5: int or double? What is the value?
أظهر الحل A3
A3. double, because one operand is a double. The value is 10.0.
Level B: Application
B1. A video is 3725 seconds long. Write two expressions that give the whole hours and the remaining seconds after removing them. Then split the remaining seconds into minutes and seconds.
أظهر الحل B1
B1. Hours: 3725 / 3600 is 1. Remaining seconds: 3725 % 3600 is 125. Then 125 / 60 is 2 minutes and 125 % 60 is 5 seconds. So 3725 seconds is 1 h 2 min 5 s.
B2. A variable int a = 9; int b = 4;. Write an expression that gives their exact quotient as a double. Say what the value is, and what (double) (a / b) would give instead.
أظهر الحل B2
B2. (double) a / b gives 2.25. (double) (a / b) divides 9 / 4 as integers first, giving 2, then converts it to 2.0.
B3. A class of 23 students sits at tables of 4. Using only integer arithmetic, how many full tables are there, how many students are at a short table, and how many tables are needed in total?
أظهر الحل B3
B3. Full tables: 23 / 4 is 5. Students at the short table: 23 % 4 is 3. Tables needed: (23 + 4 - 1) / 4 is 26 / 4, which is 6.
Level C: Challenge
C1. The last digit of a non-negative int n is n % 10. Write an expression that drops the last digit (for example 4821 becomes 482), and one that gives the last two digits.
أظهر الحل C1
C1. n / 10 drops the last digit: 4821 / 10 is 482. n % 100 gives the last two digits: 4821 % 100 is 21.
C2. int a = 100_000; int b = 100_000; What does a * b print? Explain, and write the expression that gives the correct value as a long.
أظهر الحل C2
C2. The true product is 10,000,000,000, which is larger than Integer.MAX_VALUE, so the int multiplication wraps and prints 1410065408. Fix: (long) a * b, which converts a first and gives 10000000000. (The number 1410065408 is the low 32 bits of the true result; you do not need to compute it by hand, only to recognise that the output is wrong.)
Mini Challenge
Write a program Receipt with these fixed values: int totalSeconds = 9045; and int priceCents = 2575;.
- Print the time as hours, minutes, and seconds using
/and%. - Print the price as dollars and cents using
/and%. - Print the price divided equally among 4 people as a
doublein cents (this should show a fraction). - Add a one-line comment above each calculation saying what it does.
Check your work: before running, write your predicted output on paper. The time should be 2 h 30 min 45 s. If you printed 2575 % 100, remember the leading-zero warning from Example 3 and check the case of a price such as 2505.
Summary & Next Lesson
Key takeaways
- Arithmetic operators are
+ - * / %.%is the remainder, not a percentage. - When both operands are
int,/drops the fraction (toward zero).7 / 2is3. - Make an operand a
doublebefore the division to keep decimals:7 / 2.0is3.5. n % 2 == 0tests for an even number./and%together split a quantity into whole units and a remainder.intdivision by zero throws an exception;doubledivision by zero givesInfinityorNaN.
Next lesson
Next is "Comparison and logical operators": how to ask yes/no questions such as "is n even?" properly, and combine several of them. You already used == once in this lesson, and the next lesson explains it.
Self-check
- What is
10 % 3? - What is
1 / 2, and how would you write it to get0.5? - What is
-9 / 2? - How do you test whether
nis even? - What happens for
int d = 0;with5 / d, and with5.0 / d?
أظهر الإجابات
1.0. Write1 / 2.0or1.0 / 2to get0.5.-4.9 / 2is4, and the sign carries over because the fraction is cut toward zero (-4.5 becomes -4).n % 2 == 0.5 / dthrowsArithmeticException: / by zeroand stops the program.5.0 / dgivesInfinity.
References
- Oracle, The Java Language Specification, Java SE 21, Chapter 15: Expressions. Section 15.17.2 says integer division rounds toward zero and that integer division by zero throws
ArithmeticException, and floating-point division follows IEEE 754 (infinity or NaN, no exception). Section 15.17.3 says the remainder keeps the sign of the dividend and satisfies(a/b)*b + (a%b) == a. - Oracle, The Java Tutorials: Operators. It lists the arithmetic operators and the precedence table used in Lesson 4.
- All program output above came from compiling and running the code with JDK 21. The facts about
Integer.MAX_VALUEwrapping come from BEG-009. The value1410065408in C2 came from running100_000 * 100_000with JDK 21.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.