Operators in java: Arithmetic, Bit, Assignment, Comparison, Logical And Operators Priority


Arithmetic Operators in java

Arithmetic operators in java are operators that contain numbers, i.e. values of type byte, short, int, long, float, double, or char, as operands. They are summarized below in Tables 1  and 2. The + and – operators in java can be used both as two-digit and as single-digit operators in java. Attention: The + operator can also be used to add two strings in a single package. Thus, “abcd” + “efgh” the string ‘abcdefgh’ Another special feature is the result type of arithmetic operations. By that we mean the type (i.e. byte, short, int, long, float, double, char, or String) of the result of an operation that does not match the type both operands ¨ must match. The best example is program lines such as

short a = 1;

short b = 2;

short c = a + b;

which, although apparently correct, compiles to the following give error message

Incompatible type for declaration.

Explicit cast needed to convert int to short.

Why this? To determine the result type of an arithmetic operation, the Java compiler does the following:

  • At least he calls if one of the operands is of type double – this is the case, the result type of this operation is double. The other operand is then (if necessary) converted implicitly to double and then performs the operation.
  • If this was not the case, the compiler calls whether one of the operands of type float – if this is the case, the result type of this operation is float. The other operand is then implicitly converted to float (if required) and then perform the operation.
  • If this was also not the case, then the compiler calls whether one of the operands is of type long if yes, the result type of this operation is long. The other operand is then (if necessary) implicitly converted to long and then perform the operation.
  • If none of the first three cases were found, the result type of this operation is in any case int. Both operands are then (if required) implicitly converted to int and then executed the operation.

This also shows why the above example produces an error message. the expression a + b does not contain any of the types double, float, or long, therefore the result type becomes an int. We will try this now without explicit type conversion to a variable of type short, resulting in an error message, because the value range of int is greater than the value range of short. However, the error can be easily fixed by explicitly forces a type conversion. The rows

short a = 1;

short b = 2;

short c = (short)(a + b);

can therefore be compiled without any difficulty. What do we learn from this? Either from now on we use for integer variables only type int (these problems do not appear here), or we for each arithmetic operation, ensure that the result is explicitly stated in the required Type to convert. In any case, we now know how to make mistakes of this type.

Attention: In connection with the type conversion, we want to again refer to the specifics in the context of the arithmetic operators in java.

  • If the + operator is used, a string operand (string operands), and an operand of any other type, the other operand is implicitly converted to a string.
  • the value of an arithmetic expression to be converted automatically to byte, short, or char. if it is a constant value of type int. man in this case, speaks of a constant expression whose value already when compiling (i.e. translating source code into Java byte code) can be determined. In general, a constant expression may only contain literal constants and final variables (symbolic constants) of the simple data types; or string literals (string constants). Permissible constant Ejectors are therefore exemplary

Table 1: Two-digit arithmetic operators in java

operator example Effect
+ a + b Add a and b
a – b Subtracted b from a
* a * b Multiplies a and b
`/ a / b Divides a by b
% a % b Returns the remainder of the integer division a / b

Table 2: One-digit arithmetic operators in java

operator example Function
+ + a Identity (returns the same value as a)
– a Negation (returns the negative value of a)

Example: how to use Arithmetic Operators in java:


operators in java

Bitwise operators in java:

In order to understand this category of operators in java, we must first of all how to store values in the computer. Basic a computer (or the electronics contained in a computer) only distinguish two conditions: Off or On. We arrange this task for the sake of simplicity, assign the numerical values 0 and 1. The smallest memory unit, where a computer can store exactly one of these values We know that we have one bit. To display any numbers and letters, several bits are combined to form new, larger units. 8 bits correspond to one byte, 1024 bytes to one kilobyte, 1024 kilobytes a megabyte, etc. Bitwise operators in java allow integer operands but do not work with the integer, the actual value of the operands, but only with their bits. Here too, a distinction is made between non-linear and non-linear operations. The only unary operation, the negation (represented by the symbol: WEB), supplies bit by bit always the complement of the operand, as shown in Table 3. In addition, there are three operations, the logical and (represented by &), the logical or (|) and the logical exclusive or (ˆ), the bit by bit

Table 3: Bitwise negation

a ~a
0 1
1 0

Table 4: And, or and exclusive or

a b a & b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0


as shown in Table 4. So in order to join two Bits to get the value 1 must

Both bits have the value 1 for the operation &, at the operation | at least one of the bits has the value 1 and in the operation ˆ exactly one of the bits has the value 1.

In the case of the bit-wise linking of two integer operands, these are bit operations applied to several bits (digit by digit) simultaneously. So delivers for example the program piece

because byte value 9 corresponds to the bit pattern 00001001 and byte value 3 to the bit pattern 00000011 corresponds and thus the bit-by-bit connection a & b corresponds to the bit pattern 00000001, ie the decimal byte value 1, supplies, while the bit-wise Link a | b the bit pattern 00001011, i.e. the decimal byte value 11 supplies. These Java bit operators are listed in Table 5. There are also three-shift operators in java, all of which are bits of an integer Shift the value by a specified number of places to the left or right, as shown in Table 6. Shifting the bits one place to the left or right can also be used as multiplication or division of the value with or by 2 can be interpreted.

Table 5: Bitwise operators in java

operator example Effect
~ ~ a Negates a bit by bit
& a &b Combines a and b bit by bit with a logical and
| a|b Combines a and b bit by bit by a logical or
^ a ^ b Combines a and b bit by bit by a logical or (exclusive)

Table 6: Shift operators in java

operator example Function
<< a << b Shifts the bits in a by b places to the left and fills up with 0 bits
>> a >> b Shifts the bits in a by b places to the right and fills up with the highest bit of a
>>> a  >>> b Shifts the bits in a by b places to the right and fills up with 0 bits

Example: how to use bitwise operators in java:


operators in java

Assignment operators in java:

The assignment operator = has a special position among the operators in java. It can be used to assign values ​​to a variable. For example, the Expression

a = 3;

assigns the value 3 to the variable a. To the right of the assignment mark can not only a constant value but also a variable or expression. Around You can also assign the same value to several variables at the same time form entire chains of assignment, for example

a = b = c = 5;

Here the value 5 is assigned to all three variables a, b, c. This becomes possible because every assignment is itself an expression whose value is the value of the left side, which in turn is passed on to the next left side can be.

Caution: The assignment operator = basically has nothing to do with that used in mathematics known equality relation (identity) to do the same sign = used. A mathematical expression of form

a = a + 1

for a real number a is, of course, false, the Java statement

a = a + 1;

on the other hand, is syntactically completely correct and increases the value of the variable a by 1. If one wants to make calculations with the value of a variable and the result then save in the same variable, it is often burdensome to change the variable name tap both to the left and right of the assignment operator. Therefore offers Java also uses an abbreviated notation for many binary operators. So can one instead

a = a + 1;

also shorter

a + = 1;

write. Both expressions are completely equivalent in Java, both increase the value of the variable an around 1. Table 7 summarizes all possible abbreviations together.

Table 7: Abbreviated notations for binary operators in java

Abbreviation example equivalent to
+= a += b a = a + b
-= a -= b a = a – b
*= a *= b a = a * b
/= a /= b a = a / b
%= a %= b a = a % b
&= a &= b a = a & b
|= a |= b a = a | b
^= a ^= b a = a ^ b
<<= a <<= b a = a << b
>>= a >>= b a = a >> b
>>>= a >>>= b a = a >>> b

Example: How to use Assignment Operators in java:


operators in java

Comparison operators and logical operators in java:

The so-called comparison operators form another group of operators in java. These always binary operators compare their operands with one another and always give a result of the type boolean, i.e. either true or false, back. In detail, these are the operators in java listed in Table 8. To create complex expressions, the comparison operators in java mostly linked by so-called logical operators. These are similar to the first look at the bit operators already introduced but expect logical ones.

Table 8: Comparison operators in java

operator example returns true if and only if
> a > b … a is larger than b
>= a >= b … a is greater than or equal to b
< a < b … a is smaller than b
<= a <= b … a is less than or equal to b
== a == b … a equals b
!= a != b … a is not equal to b

Operators in Java are always operands of type boolean, and their result type is also boolean. As with the bit operators, there are operators for logical And (operator &), logical or (operators | and ˆ), and negation (operator !), the effect of which is shown in Table 9.

Table 9: Logical and, or and the negation

a b a  & b a | b a ^ b !a
False False False False False True
False True False True True True
True False False True True False
True True True True False false

The operators && and || are special with them the second Operand is only evaluated if the result of the operation is not already is clear after evaluating the first operand. In the case of a && b, b only has to are then evaluated if the evaluation of results in the value true. in this case, a || b only has to be evaluated if results in the value are false. For example, if the expression (a> 15) && (b <20) is to be evaluated and the value of the variable a is just 10, the first partial expression results (a> 15) initially false. In this case, the compiler checks the value of the variable b no longer after, since the entire expression is also only false can be.

What do we get out of it now? First of all, one can through skillful exploitation these operators in java determine the execution speed of the program in individual cases increase significantly. Must have two conditions at one point in a program true, and is the result of one condition in 90% of all If false, it is advisable to have this condition checked first and to join the second via the conditional operator. Now the second has to be Condition can only be checked in the 10% of all cases in which the first condition becomes true. In all other cases, the program runs faster. Furthermore, if the conditions are not only variables but also Contain calls to methods (we will learn exactly what that is later), with help of a conditional operator achieve that certain program parts, in general, cannot be processed. But more on that later. Table 10 summarizes all logical operators in java.

Table 10: Logical operators in java

Operator example Function
& a & b Combines a and b with a logical And
&& a && b Combines a and b with a logical And (only conditional evaluation of b)
| a|b Combines a and b with a logical or
|| A || b Combines a and b with a logical or (only conditional evaluation of b)
^ a^b Combines a and b with a logical exclusive or
! !a Negates a

The takes a special position among the comparison and logical operators three-digit conditional operator?: a. Actually, it is only a shorthand one Notation for an if decision statement. As the first operand, it expects an expression with the result type boolean, as second and third expressions each, both of a numeric data type, are both of type boolean or both of type String. Returns the first If the operand returns true, the operator returns the value of its second operand back. If the first operand returns false, the value of the third operand is the result of the operation.

Example: The expression

(a == 15) ? “a is 15” :  “a is not 15”

returns the character string a is 15 if the variable a contains the value 15, and the string a is not 15 in all other cases.

Example: How to use comparison operators in java:


operators in java

Example: How to use logical operators in java:


operators in java

Increment and decrement operators in java:

Here, too, it is actually only a question of abbreviated notations of frequent terms used. To increase the content of the variable a by one, we could write – as we now know – for example:

a = a + 1;

Alternatively – we have already learned that too – the abbreviated assignment operator on, i.e.

a + = 1;

In this special case (an increase of the variable content by exactly 1) it is possible now an even shorter notation, namely


The increment operator ++ is therefore unrecognized and increases the value of its operand at one. In the same way, the decrement operator decreases -, also a non-arid one Operator, the value of its operand by one. Both operators are only allowed to Variables are applied. What needs to be considered? As already mentioned, both operators can both can be used in both prefix and postfix notation. If the operator is in an isolated statement – as in the example above – is used, both Notations equivalent. However, if the increment or decrement operator is part of a larger expression, so the notation has a decisive influence on the result of the expression.

If the prefix notation is used, the value of the variable is first increased or decreased and then the expression is evaluated. In the same way, the Postfix Notation, the expression is evaluated first and only then the increment or decrement carried out.


a = 5;

b = a ++;

c = 5;

d = –c;

After this program segment has been executed, b contains the value 5, since first the Expression is evaluated and then the increment is executed. d against it contains the value 4 since the decrement is carried out first and then the Expression is evaluated. In the end, a has the value 6 and c has the value 4.

Example: how to use increment and decrement operators in java:


operators in java

Priority and evaluation order of the operators in java:

So far we have only considered all operators in isolation, i.e. our expressions each contained only one operator. However, if you use several operators In an expression, the question arises in what order each operation is performed. This is due to the priorities of the individual operators set. Operations with a higher priority always take precedence over operations lower priority is carried out if parentheses (see below) do not indicate otherwise regulate. Have multiple two-digit operations in the same expression stand, the same priority, then – except for assignment operators – always from evaluated left to right. The assignment operator = and all abbreviated one’s Assignment operators – i.e. + =, – =, etc. – are used when they are next to each other in occur in an expression, but evaluated from right to left. Table 11 contains all the operators that we have come to know so far, in order according to their priority. With the top group of operators in java with the highest Priority (15). In practice, this means for us that we can safely do “point-to-point calculation” can use without worrying about what priorities have to. Since multiplicative operators in java have a higher priority than additive operators, are expressions such as

4 + 3 * 2

evaluated correctly as expected (here: the result is 10, not 14). Beyond that but we should rather use one pair of brackets too many rather than too few to guarantee the desired order of execution of the operations. In fact, just like in mathematics, we can use round brackets () Determine the sequence of operations clearly, regardless of the priority assigned to them.

Related Article:

Java Constant and Constant Enumerations (Enums)

Input and Output Data in java With Examples


Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button