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

Introduction to Java Operators: Boolean, Arithmetic, Bitwise

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

What are the 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, unary minus.

Java operators in the CodeGym course

Several lectures are devoted to Java operators at the fourth level of the first quest - Java Syntax. In particular, conditional operators, of type boolean . The course has 22 tasks that will help you understand the work of comparison operators, conditional, logical operators.

Operations on numbers in Java

The most common operation that programmers perform on numbers is to assign 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: Boolean, Arithmetic, Bitwise - 2The first four operators should not raise questions: everything is the same as in mathematics. The last operator, the remainder of the division, also doesn't do anything super complex. For example, if we divide 24 by 7, we get 3 integers and 3 as a 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: Boolean, 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. Consider 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 xthe sum of the current value of the variable xand one to the value. There are explanations in the comments for each line. This procedure is called incrementing or incrementing a variable. The increment 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: Boolean, Arithmetic, Bitwise - 4
In addition to binary operators, Java has unary arithmetic operators.
Table 2. Unary arithmetic operators:
Introduction to Java Operators: Boolean, 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: Boolean, 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. Suppose we have a variable:
int a = 2;
Then:
Table 3. Increment-Decrement Operators:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 5Demonstration:
Introduction to Java Operators: Boolean, 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: Boolean, 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: Boolean, Arithmetic, Bitwise - 10

Boolean operations in Java

Consider the logical operations and the 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 one operand. All other operations are binary. Consider the truth tables of these operations. Here, 0 is the equivalent of false in Java, and 1 is the value of true .
Table 5. Truth table of the negation operator (NOT)
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 7
Table 6. Truth table of the conjunction operator (AND)
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 8
Table 7. Truth table of the disjunction operator (OR)
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 9
Table 8. Truth table of the modulo addition (XOR) operator
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 10Java has the same boolean operations:
  • !is the negation operator;
  • &&- logical AND operator (abbreviated);
  • ||- logical OR operator (abbreviated);
  • &- bitwise AND operator;
  • |- bitwise OR operator;
  • ^is a bitwise XOR operator.
Let's look at the difference between bitwise and shorthand operators below, while let's convert all 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 Boolean operators only apply to variables boolean. In our case, we applied them directly to values, but you can use them with booleanvariables as well:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 15
And for booleanexpressions:
Introduction to Java Operators: Boolean, 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 will 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 = ?
xIt can take any boolean value here . 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: Boolean, Arithmetic, Bitwise - 17
Sometimes the result of an expression can be calculated already by the first operand. This is what distinguishes the abbreviated operators &&and ||. In expressions like those described above, they do not evaluate the value of the second operand. Here is a small example:
Introduction to Java Operators: Boolean, 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, we got to the most interesting part: bitwise operations. As the name implies, these are operations that are performed on bits. But before we dive into this topic, it is worth talking about related areas.

Representation of numbers in binary system

Numbers, like any other information in the program, are stored in the computer's memory in binary code. Binary code is a set of zeros and ones. Each zero or one is a unit of information called a bit.

According to Wikipedia:

Bit (from the English binary digit - a binary number; also a play on words: English bit - a piece, a particle) - a unit of measurement of the amount of information. 1 bit of information is a symbol or signal that can take on two values: on or off, yes or no, high or low, charged or uncharged; in binary 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. And integers are stored in computer memory as a set of bits. We can say that a computer translates any information into a binary number system (into 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 characters: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. With the help of these characters we keep score. After 9 comes 10, after 19 - 20, after 99 - 100, after 749 - 750. That is, we use a combination of the available 10 characters and can use them to count "from zero to lunch." In the binary system, instead of ten characters, there are only two - 0, 1. But by combining these characters 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: Boolean, Arithmetic, Bitwise - 11As you can see, everything is not so difficult. In addition to bits, there are other familiar units of information - bytes , kilobytes , megabytes , gigabytes , and so on. 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 get back to Java. There is such an integer data type - byte. This type can take values ​​from -128 to 127, and one number in computer memory takes exactly 8 bits, or 1 byte. One number of this type occupies 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 256 different values ​​(128 negative, 127 positive and 1 zero). Each number value bytecorresponds to a unique set of eight bits. This is the case not only with type byte, but with all integer types. Typebytecited as the smallest. The following table lists all Java integer types and their memory space: Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 12Consider the int. It can store 2147483648 negative values, 2147483647 positive values ​​and one zero. Total:

2147483648 + 2147483647 + 1 = 4294967296.
This type occupies 32 bits in the computer memory. The number of possible combinations from a set of 32 zeros and ones is:
232 = 4294967296.
Same number as the number of values ​​that can fit in the 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 the binary number system. Let's see how easy it can be done using the Java language. Let's learn from the example of the type int. This type has its own wrapper class - Integer. And he has - toBinaryStringwho will do all the work for us:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 21
Voila - it's not that hard. However, something needs to be clarified. intnumber is 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 00000000000000000000000000001010 in the console. But for readability, all leading zeros are omitted. It's not that hard, as long as you don't ask yourself: what about negative numbers? He perceives information only in the binary system. It turns out that the minus sign must also be written in binary code. This can be done with direct or additional code.

Direct code

A way of representing numbers in the binary number system, in which the most significant digit (leftmost bit) is assigned to the sign of the number. If the number is positive, the leftmost bit is set to 0, if negative, 1.
Consider this using an 8-bit number as an example:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 13The approach is simple and understandable in principle. However, it has disadvantages: there are difficulties with performing mathematical operations. For example, adding negative and positive numbers. They cannot be folded unless additional manipulations are carried out.

Additional code

By using additional code, the disadvantages of direct code can be avoided. There is a simple algorithm for obtaining an additional number code. Let's try to get the additional code of the number -5. Let's represent this number with the help of two's complement code in binary number system. Step 1. We get the representation of a negative number using a direct code. For -5 it will be 10000101. Step 2. Invert all bits except the sign bit. Let's replace all zeros with ones, and ones with zeros everywhere except for the leftmost bit.

10000101 => 11111010
Step 3. Add one to the resulting value:

11111010 + 1 = 11111011
Ready. We got the value of the number -5 in the binary number system using two's complement. This is important for understanding what follows, because Java uses two's complement to store negative numbers in bits.

Types of Bitwise Operations

Now that we have dealt with all the introductory things, let's talk about bitwise operations in Java. A bitwise operation is performed on integers and results in 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: Boolean, Arithmetic, Bitwise - 14As we have already found out, numbers can be represented as a set of bits. Bitwise operations perform operations on just every bit of such a representation. Let's take NOT, AND, OR, XOR. Recall that recently we considered truth tables, only for logical operands. In this case, the same operations are applied to each bit of an integer.

Bitwise unary operator NOT ~

This operator replaces all zeros with ones, and all ones with zeros. Suppose we have the number 10 in decimal. 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: Boolean, Arithmetic, Bitwise - 15Let's take a look at how it looks 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 will be output to the console:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 25
In the first line, we got the value in binary without leading zeros. Although 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. That is why we see so many leading units. These are the 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: Boolean, Arithmetic, Bitwise - 26

Bitwise AND Operator

This operator is applicable to two numbers. It performs an operation ANDbetween the bits of each number. Consider an example: Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 16This operation is performed on two numbers. Example in Java code:
Introduction to Java Operators: Boolean, 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: Boolean, Arithmetic, Bitwise - 17Now let's look at what it would look like in IDEA:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 30

Bitwise Exclusive OR (XOR)

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

Bit 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? Consider the example of the operation 10 << 1 Introduction to Java Operators: Boolean, 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. With this operation, the value of the most significant bit (leftmost) is lost. And the least significant bit (rightmost) is filled with zero. What can be said about this operation?
  1. By shifting the bits of the number Xby Nbits to the left, we multiply the number Xby 2 N .

    Here is an example:

    Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 34
  2. But! We can change the sign of a number if a bit with a value of 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: Boolean, Arithmetic, Bitwise - 35

Bit shift right

This operator applies to two operands. Those. in operation x >> y, the bits of the number xwill shift ypositions to the right. Let's consider another example. We will schematically analyze the operation 10 >> 1. Let's shift all bits of number 10 one position to the right: Introduction to Java Operators: Boolean, 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 set the same as in the original number. Example with a negative number: Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 21The rightmost bit is lost, and the leftmost bit is copied from the original number as an honorific indicator of the sign of the number. How to implement all this in IDEA? In principle, nothing complicated, just take and move:
Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 38
Now. What can be said about 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 down to minus infinity (down). But this only works if we shift the bits by exactly 1. And if by 2 bits, we divide by 4. By 3 bits, we divide by 8. By 4 bits, we divide by 16. See? Powers of 2... When shifting a number Xby Nbits to the right, we divide the number Xby 2 to the power of 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:
    • shiftOperationResultwe write the result of shifting the number 2048 by i bits to the right into the variable ;

    • in the variable devideOperationResultwe write the result of dividing the number 2048 by 2 to the power of i.

  3. Pairwise output the two obtained values.

The result of running the program is: 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 bit shift to the right preserves the sign of the number (the most significant bit retains its value), in the case of a right shift with zero padding, this does not happen. And the most significant bit is filled with zero. Let's see what it looks like: Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 22

Operation Precedence in Java

Just like in mathematics, Java has operator precedence. The table below shows the priority (from highest to lowest) of the operations we have considered. Introduction to Java Operators: Boolean, Arithmetic, Bitwise - 23

Useful use cases

Determining the parity of a number

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

Finding the maximum element in an array

Introduction to Java Operators: Boolean, 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