Аккаунт Войти / Регистрация
Тема
Размер текста
Arithmetic operators

Arithmetic operators

In this lesson, we will talk about arithmetic operations and operators.

In programming, operators are commands that perform specific actions: mathematical, string, logical, or comparison operations. The arithmetic operators in Java include: + (addition), - (subtraction), * (multiplication), / (division), and % (modulus). These operators work similarly to other programming languages.

The precedence of operations in Java is the same as in mathematics:
First group: /, *, %
Second group: +, -

Restrictions

The operators * (multiplication) and / (division) have a higher precedence and apply to any numeric types, including char. However, division by zero is not allowed — the program will throw an exception ArithmeticException.

Data types in Java have strict ranges of values. For example:

byte xyz = 125 + 15; // Error — exceeded byte range (-128 to 127)

The byte type takes 8 bits, and if the result exceeds this range, an error occurs.

Data in a computer is stored in the form of zeros and ones (in binary system). That is why the data type defines how much memory is allocated for storing a value. If you choose a type that is too small, you may encounter a lack of precision or loss of accuracy.

Example of Division

If you divide integers, the result will also be an integer (the fraction part is discarded):

byte ab = 12 / 9; // Result: 1
If data type specifics are not taken into account, multiplication can lead to loss of precision, and division can lead to loss of accuracy.

Modulo

The operator % returns the remainder of the division. For example:

13 % 9; // Result: 4

Operands (for example, 13 and 9) are most often integers, but the operator can also be applied to floating-point numbers. It is important to remember: the sign of the result depends on the left operand.

How the % operator works

It subtracts the right operand from the left until the result is less than the right:


15 % 4 = 3
19 % 5 = 4
22 % 6 = 4
For example: 15 - 4 = 11 (>4), 11 - 4 = 7 (>4), 7 - 4 = 3 (<4), therefore 15 % 4=3.

Incrementing and Decrementing

Incrementing (from English increment — increase) is denoted by a double plus ++. Decrementing (decrease) is denoted by a double minus --.

Prefix Form:


int a = 5;

++a; // a = 6 — incrementing
--a; // a = 5 — decrementing

Postfix Form:


int a = 5;

a++; // a = 6 — incrementing
a--; // a = 5 — decrementing
The difference between prefix and postfix forms manifests when the operation is performed in an expression — prefix modifies the value immediately, postfix — after using the variable.

Homework

  1. Create variables of different numeric types (byte, int, float, double).
  2. Try to perform operations with them: +, -, *, /, %.
  3. Check what happens when dividing by zero.
  4. Try applying ++ and -- in prefix and postfix forms.

Test — How well did you understand the lesson?

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Java under the Microscope: Stack, Heap, and GC using Code Examples
Diagram - Java Memory Model - Heap / Non-Heap / Stack Heap (memory for objects) Creates objects via new. Young Generation: Eden + Survivor. Old Generation: objects that have survived several GC c…
Go vs Java - comparison of memory models: happens-before, visibility, reorder, synchronization events, write/read barriers
Memory model is a layer between the program and the processor. Modern CPUs aggressively optimize execution: instructions may be reordered, data may be stored in core caches, and operations may be perf…
Java v25: Choosing the Right Multithreading for Any Task
Introduction The Java world is rapidly evolving, and with each version, new tools are emerging for effectively working with multithreading, collections, and asynchrony. Java 25 brings powerful feature…

Новые статьи:

Concurrency is not about “starting many threads”. It’s about agreements between them. Imagine a restaurant kitchen: — cooks (threads / goroutines) — orders (tasks) — and the main question: how do th…
When HashMap starts killing production: the engineering story of ConcurrentHashMap
Imagine a typical production service. 32 CPU hundreds of threads configuration / session / rate limits cache tens of thousands of operations per second And somewhere inside — a regular Map. At first…
Zero Allocation in Java: what it is and why it matters
Zero Allocation — is an approach to writing code in which no unnecessary objects are created in heap memory during runtime. The main idea: fewer objects → less GC → higher stability and performance. …