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
- Create variables of different numeric types (
byte,int,float,double). - Try to perform operations with them:
+,-,*,/,%. - Check what happens when dividing by zero.
- Try applying
++and--in prefix and postfix forms.
Test — How well did you understand the lesson?
Оставить комментарий
Useful Articles:
New Articles: