JavaRush /Java Blog /Random EN /Introduction to Java Operators: Logical, Arithmetic, Bitw...

Introduction to Java Operators: Logical, Arithmetic, Bitwise

Published in the Random EN group
Let's talk about operations in Java: numeric, logical, bitwise. This is a theoretical basis that is definitely needed to learn how to program. Introduction to Java Operators: Logical, Arithmetic, Bitwise - 1

What are the types of operators in Java?

For any operation we need at least two things:
  • operator;
  • operand.
An example of an operator would be a simple plus in the operation of adding two numbers. And the numbers added to each other will be operands in this case. So, with the help of operators, we perform operations on one or more operands. Operators that perform operations on two operands are called binary. For example, adding two numbers. Operators that perform operations on a single operand are called unary. For example, a unary minus.

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:
Table 1. Binary arithmetic operators
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 2The 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:
System.out.println(24 % 7); // prints 3
Here are examples from the official Oracle documentation site: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 3This 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 xand assigned it a value of zero. Next, in each line we assign a value xto the sum of the current value of the variable xand 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:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 4
In addition to binary operators, Java has unary arithmetic operators.
Table 2. Unary arithmetic operators:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 4Example of unary plus and minus:
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);
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 6
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:
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:
Table 3. Increment-decrement operators:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 5Demonstration:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 8
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
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 9Examples:
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:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 10

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).
The negation operator is unary and applies to a single operand. All other operations are binary. Let's consider the truth tables of these operations. Here 0 is the equivalent of false in Java, and 1 is the equivalent of true .
Table 5. Negation Operator Truth Table (NOT)
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 7
Table 6. Truth table of the conjunction operator (AND)
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 8
Table 7. Truth table of the disjunction operator (OR)
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 9
Table 8. Truth table of modulo addition operator (XOR)
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 10Java has the same logical operations:
  • !— negation operator;
  • &&— logical AND operator (short);
  • ||— logical OR operator (short);
  • &— bitwise AND operator;
  • |— bitwise OR operator;
  • ^— bitwise exclusive OR operator.
Let's look at the difference between bitwise and shorthand operators a little further below, while let's convert all the truth tables into Java code:
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 booleanvariables. In our case, we applied them directly to values, but you can also use them with booleanvariables:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 15
And to booleanthe expressions:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 16
Now, we have shorthand operators ( &&, ||) 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 xcan 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.
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 17
Sometimes the result of an expression can be calculated from the first operand. This is what distinguishes the abbreviated operators &&and ||. In expressions similar to those described above, they do not evaluate the value of the second operand. Here's a small example:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 18
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.

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.
Let's demonstrate counting from 0 to 15 in decimal and binary:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 11As 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:

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 bytecomputer memory. And here the names coincide not by chance. As we remember, 1 byte can store 256 different values. And one type number bytecan take on 256 different values ​​(128 negative, 127 positive and 1 zero). Each number value bytehas a unique set of eight bits. This is the case not only with type byte, but with all integral types. The type byteis given as an example as the smallest. The table below shows all the Java integer types and the memory space they occupy: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 12Consider 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:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 21
Voila - it's not that complicated. But still, something needs to be clarified. intthe 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.
Let's look at this using an 8-bit number as an example:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 13The 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.

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: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 14As 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 take NOT, 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: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 15Let'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:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 25
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.
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 26

Bitwise AND operator

This operator applies to two numbers. It performs an operation ANDbetween the bits of each number. Let's look at an example: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 16This operation is performed on two numbers. Example in Java code:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 28

Bitwise OR operator

OR applies to two numbers. It performs an OR operation between the bits of each number: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 17Now let's take a look at what this would look like in IDEA:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 30

Bitwise operation, exclusive OR (XOR)

Let's look at the same example, but with a new operation: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 18Example code:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 32

Bitwise shift left

This operator is applicable to two operands, that is, in the operation x << y, the bits of the number xwill shift ypositions to the left. What does it mean? Let's look at the example of the operation. 10 << 1 Introduction to Java Operators: Logical, Arithmetic, Bitwise - 19The 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?
  1. By shifting the bits of a number Xby Nbits to the left, we multiply the number Xby 2 N .

    Here's an example:

    Introduction to Java Operators: Logical, Arithmetic, Bitwise - 34
  2. But! The sign of the number may change if the bit with the value 1 takes the leftmost position.

  3. If you shift left indefinitely, the number will simply turn into 0. Let's demonstrate points 2 and 3:

    Introduction to Java Operators: Logical, Arithmetic, Bitwise - 35

Bitwise shift right

This operator applies to two operands. Those. in the operation x >> y, the bits of the number xwill shift ypositions 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: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 20During 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: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 21The 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:
Introduction to Java Operators: Logical, Arithmetic, Bitwise - 38
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 Xto Nthe right by bits, we divide the number Xby 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?
  1. A loop in which the variable i is incremented from 1 to 10.

  2. Each iteration we calculate 2 values:
    • We write into the variable shiftOperationResultthe result of shifting the number 2048 by i bits to the right;

    • devideOperationResultWe write the result of dividing the number 2048 by 2 to the i power into a variable .

  3. We display the two obtained values ​​in pairs.

The result of executing the program is as follows: 1024 - 1024 512 - 512 256 - 256 128 - 128 64 - 64 32 - 32 16 - 16 8 - 8 4 - 4 2 - 2

Bitwise right shift with zero padding

While a normal right shift preserves the sign of the number (the most significant bit retains its value), a zero-fill right shift does not. And the most significant bit is filled with zero. Let's see what it looks like: Introduction to Java Operators: Logical, Arithmetic, Bitwise - 22

Precedence of operations in Java

Like mathematics, Java has precedence of operations. The table below shows the priority (from highest to lowest) of the operations we considered. Introduction to Java Operators: Logical, Arithmetic, Bitwise - 23

Useful examples of use

Determining the parity of a number

Introduction to Java Operators: Logical, Arithmetic, Bitwise - 24

Finding the maximum element in an array

Introduction to Java Operators: Logical, Arithmetic, Bitwise - 25To find the minimum element, simply change the comparison sign in the right place.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION