Let's talk about operations in Java: numeric, logical, bitwise. This is a theoretical basis that is definitely needed to learn how to program.
Table 1. Binary arithmetic operators
The first four operators should not raise any questions: everything is the same as in mathematics. The last operator, the remainder of division, also doesn't do anything too complicated. For example, if we divide 24 by 7, we get 3 whole numbers and 3 remainder. It is the remainder that this operator will return:
In addition to binary operators, Java has unary arithmetic operators.
Table 2. Unary arithmetic operators:
Example of unary plus and minus:
The increment and decrement operations are essentially simple. In the first case, the variable is increased by 1, in the second, the variable is decreased by 1. The example is below:
Table 3. Increment-decrement operators:
Demonstration:
In addition to arithmetic, there are comparison operations (of two numbers). The result will always be true or false ( true / false ).
Table 4. Comparison operators
Examples:
Table 5. Negation Operator Truth Table (NOT)
Table 6. Truth table of the conjunction operator (AND)
Table 7. Truth table of the disjunction operator (OR)
Table 8. Truth table of modulo addition operator (XOR)
Java has the same logical operations:
And to
Now, we have shorthand operators (
Sometimes the result of an expression can be calculated from the first operand. This is what distinguishes the abbreviated operators
In the case of shorthand operators, the second part of the expression is not evaluated. But this happens only when the result of the expression is already obvious from the first operand.
Let's demonstrate counting from 0 to 15 in decimal and binary:
As you can see, everything is not so complicated. In addition to bits, there are other familiar units of information - bytes , kilobytes , megabytes , gigabytes , etc. You probably know that there are 8 bits in 1 byte . What does it mean? This means that 8 bits in a row occupy 1 byte. Here are examples of what bytes can be:
Voila - it's not that complicated. But still, something needs to be clarified.
Let's look at this using an 8-bit number as an example:
The approach is simple and, in principle, understandable. However, it has disadvantages: difficulties in performing mathematical operations. For example, with the addition of negative and positive numbers. They cannot be folded unless additional manipulations are carried out.
In the first line we got the value in binary number system without leading zeros. Even though we don’t see them, they are there. This is evidenced by the second line, in which all the bits were transformed into reverse ones. This is why we see so many leading units. These are former leading zeros that were ignored by the compiler when printed on the first line. Here is a small program that also displays leading zeros for clarity.
Now. What can you say about the numbers that are shifted to the right? They are divisible by 2. Each time we shift one bit to the right, we divide the original number by 2. If the number is not divisible by 2, the result will be rounded towards minus infinity (down). But this only works if we shift the bits by exactly 1. And if by 2 bits, divide by 4. By 3 bits, divide by 8. By 4 bits, divide by 16. See? Powers of 2... When we shift a number
- What are the types of operators in Java?
- Java Operators in JavaRush Course
- Number operations in Java
- Logical Operations in Java
- Bitwise operations in Java
- Precedence of operations in Java
- Useful examples of use
What are the types of operators in Java?
For any operation we need at least two things:- operator;
- operand.
Java Operators in JavaRush Course
Several lectures are devoted to Java operators at the fourth level of the first quest - Java Syntax. In particular, conditional operators such as boolean . The course contains 22 tasks that will help you understand the work of comparison operators, conditional operators, and logical operators.Number operations in Java
The most common operation that programmers perform on numbers is assigning a numeric value to a variable. She, like the operator,=
is familiar to you:
int a = 1;
int b = 2;
int c = 3;
There are also arithmetic operations. They are carried out using binary arithmetic operators:
System.out.println(24 % 7); // prints 3
Here are examples from the official Oracle documentation site: This program will output the following: 1 + 2 = 3 3 - 1 = 2 2 * 2 = 4 4 / 2 = 2 2 + 8 = 10 10 % 7 = 3 Java allows you to combine: for example, operators assignments and arithmetic operators. Let's look at an example:
int x = 0;
x = x + 1; // x = 0 + 1 => x = 1
x = x + 1; // x = 1 + 1 => x = 2
x = x + 1; // x = 2 + 1 => x = 3
Here we have defined a variable x
and assigned it a value of zero. Next, in each line we assign a value x
to the sum of the current value of the variable x
and one. There are explanations in the comments for each line. This procedure is called growing or incrementing a variable. The incrementing operation from the example above can be replaced with a similar one using a combination of operators:
int x = 0;
x += 1; // x = 0 + 1 => x = 1
x += 1; // x = 1 + 1 => x = 2
x += 1; // x = 2 + 1 => x = 3
You can combine the assignment operator with any arithmetic operator:
int x = 0;
x += 10; // x = 0 + 10 => x = 10
x -= 5; // x = 10 - 5 => x = 5
x *= 5; // x = 5 * 5 => x = 25
x /= 5; // x = 25 / 5 => x = 5
x %= 3; // x = 5 % 3 => x = 2;
Let's demonstrate how the last example works:
int x = 0;
x = (+5) + (+15); // Parentheses for clarity, it is possible without them
System.out.println("x = " + x);
int y = -x;
System.out.println("y = " + y);
int x = 9;
x++;
System.out.println(x); // 10
int y = 21;
y--;
System.out.println(y); // 20
There are two types of these operations - postfix and prefix. In the first case, the operator is written after the variable, in the second case, before the variable. The only difference is when the increment or decrement operation is performed. Example and description in the table below. Let's say we have a variable:
int a = 2;
Then:
int a = 1;
int b = 2;
boolean comparisonResult = a == b;
System.out.println("a == b :" + comparisonResult);
comparisonResult = a != b;
System.out.println("a != b :" + comparisonResult);
comparisonResult = a > b;
System.out.println("a > b :" + comparisonResult);
comparisonResult = a >= b;
System.out.println("a >= b :" + comparisonResult);
comparisonResult = a < b;
System.out.println("a < b :" + comparisonResult);
comparisonResult = a <= b;
System.out.println("a <= b :" + comparisonResult);
Demonstration:
Logical Operations in Java
Let's look at the logical operations and truth tables of each of them:- negation operation (
NOT
); - conjunction operation, logical AND (
AND
); - disjunction operation, logical OR (
OR
); - modulo addition operation, exclusive OR (
XOR
).
!
— negation operator;&&
— logical AND operator (short);||
— logical OR operator (short);&
— bitwise AND operator;|
— bitwise OR operator;^
— bitwise exclusive OR operator.
public class LogicDemo {
public static void main(String[] args) {
notExample();
andExample();
orExample();
xorExample();
}
public static void notExample() {
System.out.println("NOT EXAMPLE:");
System.out.println("NOT false = " + !false);
System.out.println("NOT true = " + !true);
System.out.println();
}
public static void andExample() {
System.out.println("AND EXAMPLE:");
System.out.println("false AND false = " + (false & false));
System.out.println("false AND true = " + (false & true));
System.out.println("true AND false = " + (true & false));
System.out.println("true AND true = " + (true & true));
System.out.println();
}
public static void orExample() {
System.out.println("OR EXAMPLE:");
System.out.println("false OR false = " + (false | false));
System.out.println("false OR true = " + (false | true));
System.out.println("true OR false = " + (true | false));
System.out.println("true OR true = " + (true | true));
System.out.println();
}
public static void xorExample() {
System.out.println("XOR EXAMPLE:");
System.out.println("false XOR false = " + (false ^ false));
System.out.println("false XOR true = " + (false ^ true));
System.out.println("true XOR false = " + (true ^ false));
System.out.println("true XOR true = " + (true ^ true));
System.out.println();
}
}
This program will display: NOT EXAMPLE: NOT false = true NOT true = false AND EXAMPLE: false AND false = false false AND true = false true AND false = false true AND true = true OR EXAMPLE: false OR false = false false OR true = true true OR false = true true OR true = true XOR EXAMPLE: false XOR false = false false XOR true = true true XOR false = true true XOR true = false Logical operators apply only to boolean
variables. In our case, we applied them directly to values, but you can also use them with boolean
variables:
boolean
the expressions:
&&
, ||
) and similar bitwise operators ( &
, |
). What is the difference between them? First, bitwise can be applied to integers. We'll talk about this a little later. And secondly, some are abbreviated, while others are not. To understand what abbreviation looks like, let's look at the expression:
false AND x = ?
true OR x = ?
This x
can take any Boolean value. And in general, according to the laws of logic and truth tables, regardless of whether it is x
true or false , the result of the first expression will be false , and the result of the second will be true . Look.
&&
and ||
. In expressions similar to those described above, they do not evaluate the value of the second operand. Here's a small example:
Bitwise operations in Java
Well, here we come to the most interesting part: bitwise operations. As the name suggests, these are operations that are performed on bits. But before we dive into this topic, it's worth talking about related areas.Representation of numbers in the binary number system
Numbers, like any other information in a program, are stored in computer memory in binary code. Binary code is a set of zeros and ones. Each zero or one represents a unit of information called a bit.According to Wikipedia:
A bit (from the English binary digit - binary number; also a play on words: English bit - piece, particle) is a unit of measurement of the amount of information. 1 bit of information is a symbol or signal that can take on two meanings: on or off, yes or no, high or low, charged or uncharged; in the binary system it is 1 (one) or 0 (zero).What kind of data do bitwise operators work with?
Bitwise operations in Java are performed only on integers. Integers are stored in computer memory as a set of bits. We can say that a computer converts any information into a binary number system (a set of bits) and only then interacts with it. But how does the binary number system work? In the decimal number system we have only 10 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. We use these symbols to count. After 9 comes 10, after 19 - 20, after 99 - 100, after 749 - 750. That is, we use a combination of the available 10 symbols and can use them to count “from zero to lunch.” In the binary number system, instead of ten symbols, there are only two - 0, 1. But by combining these symbols according to the same principle as in the decimal system, we can count indefinitely.
00000000 - 1 byte
10110010 - 1 byte
01011011 - 1 byte
The number of possible non-repeating combinations of bits in one byte is 256 (2 8 = 256). But let's return closer to Java. There is such an integer data type - byte
. This type can take values from -128 to 127 and one number in the computer memory takes up exactly 8 bits, or 1 byte. One number of this type takes up exactly 1 byte
computer memory. And here the names coincide not by chance. As we remember, 1 byte can store 256 different values. And one type number byte
can take on 256 different values (128 negative, 127 positive and 1 zero). Each number value byte
has a unique set of eight bits. This is the case not only with type byte
, but with all integral types. The type byte
is given as an example as the smallest. The table below shows all the Java integer types and the memory space they occupy: Consider the type int
. It can store 2147483648 negative values, 2147483647 positive values, and one zero. Total:
2147483648 + 2147483647 + 1 = 4294967296.
This type takes up 32 bits in computer memory. The number of possible combinations from a set of 32 zeros and ones is:
232 = 4294967296.
The same number as the number of values the type can hold int
. This is just a demonstration of the relationship between the range of values of a data type and its size (number of bits in memory). Any number of any type in Java can be converted to binary. Let's see how easily this can be done using the Java language. We will learn from the example of type int
. This type has its own wrapper class - Integer
. And he has one toBinaryString
, which will do all the work for us:
int
the number takes 32 bits. But when we print the number 10 in the example above, we see 1010 in the console. This is because leading zeros are not printed. If they were displayed, instead of 1010 we would see 000000000000000000000000000001010 in the console. But for ease of perception, all leading zeros are omitted. Not that hard until you ask yourself: what about negative numbers? It perceives information only in the binary system. It turns out that the minus sign also needs to be written in binary code. This can be done using direct or complementary code.
Direct code
A method of representing numbers in the binary number system, in which the most significant bit (the leftmost bit) is allocated to the sign of the number. If the number is positive, the leftmost bit is written 0, if negative - 1.Additional code
By using additional code, you can avoid the disadvantages of direct code. There is a simple algorithm to obtain the additional code of a number. Let's try to get the additional code for the number -5. Let's represent this number using two's complement code in the binary number system. Step 1. We obtain a representation of a negative number using direct code. For -5 it will be 10000101. Step 2. Invert all digits except the sign digit. Let's replace all zeros with ones, and ones with zeros everywhere except the leftmost bit.
10000101 => 11111010
Step 3. Add one to the resulting value:
11111010 + 1 = 11111011
Ready. We got the value of -5 in binary number system using two's complement code. This is important for understanding the following material, since Java uses two's complement code to store negative numbers in bits.
Types of bitwise operations
Now that we have dealt with all the introductions, let's talk about bitwise operations in Java. A bitwise operation is performed on integers and its result is an integer. In the process, the number is converted to binary, an operation is performed on each bit, and the result is converted back to decimal. The list of operations is in the table below: As we have already found out, numbers can be represented as a set of bits. Bitwise operations perform operations on exactly each bit of such a representation. Let's takeNOT
, AND
, OR
, XOR
. Recall that we recently looked at truth tables only for logical operands. In this case, the same operations are applied to each bit of the integer.
Bitwise unary operator NOT ~
This operator replaces all zeros with ones, and all ones with zeros. Let's say we have the number 10 in decimal notation. In binary, this number is 1010. If we apply the unary bitwise negation operator to this number, we get something like this: Let's take a look at what it looks like in Java code:public static void main(String[] args) {
int a = 10;
System.out.println(" a = " + a + "; binary string: " + Integer.toBinaryString(a));
System.out.println("~a = " + ~a + "; binary string: " + Integer.toBinaryString(~a));
}
Now let's see what is displayed in the console:
Bitwise AND operator
This operator applies to two numbers. It performs an operationAND
between the bits of each number. Let's look at an example: This operation is performed on two numbers. Example in Java code:
Bitwise OR operator
OR applies to two numbers. It performs an OR operation between the bits of each number: Now let's take a look at what this would look like in IDEA:Bitwise operation, exclusive OR (XOR)
Let's look at the same example, but with a new operation: Example code:Bitwise shift left
This operator is applicable to two operands, that is, in the operationx << y
, the bits of the number x
will shift y
positions to the left. What does it mean? Let's look at the example of the operation. 10 << 1
The result of the operation will be the number 20 in the decimal system. As you can see from the diagram above, all bits are shifted left by 1. During this operation, the value of the most significant bit (the leftmost bit) is lost. And the least significant bit (the rightmost bit) is filled with zero. What can you say about this operation?
-
By shifting the bits of a number
X
byN
bits to the left, we multiply the numberX
by 2 N .Here's an example:
-
But! The sign of the number may change if the bit with the value 1 takes the leftmost position.
-
If you shift left indefinitely, the number will simply turn into 0. Let's demonstrate points 2 and 3:
Bitwise shift right
This operator applies to two operands. Those. in the operationx >> y
, the bits of the number x
will shift y
positions to the right. Let's look at another example. Let us schematically analyze the operation 10 >> 1
. Let's shift all the bits of the number 10 one position to the right: During the shift operation, we lose the right bits. They simply disappear. The leftmost bit is the sign of the number (0 is positive, 1 is negative). Therefore, in the final value it is placed the same as in the original number. Example with a negative number: The rightmost bit is lost, and the leftmost bit is copied from the original number, as an honorary sign of the number. How to do all this in IDEA? In principle, nothing complicated, just take it and move it:
X
to N
the right by bits, we divide the number X
by 2 to the power of 2 N
. Demonstration:
public class BitOperationsDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int shiftOperationResult = 2048 >> i;
int devideOperationResult = 2048 / (int) Math.pow(2, i);
System.out.println(shiftOperationResult + " - " + devideOperationResult);
}
}
}
What's going on here?
-
A loop in which the variable i is incremented from 1 to 10.
- Each iteration we calculate 2 values:
-
We write into the variable
shiftOperationResult
the result of shifting the number 2048 by i bits to the right; -
devideOperationResult
We write the result of dividing the number 2048 by 2 to the i power into a variable . -
We display the two obtained values in pairs.
GO TO FULL VERSION