Java #8 - Operators

Java #8 - Operators

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Assignment Operator

The assignment operator "=" is used to assign a value on its right side to the operand to its left: int a = 5;

Arithmetic Operators

Arithmetic operators are used in mathematical expressions to perform addition, subtraction, multiplication, and division. The operands of the arithmetic operators must be of numeric type (int, short, byte, long, float, double, char).

img-2.png

  • When we divide integer value, there will be no fractional part returned
  • % operator returns the remainder of a division operator

Arithmetic Compound Assignment Operators

We can also combine arithmetic operations with an assignment.

x = x + 2 can be re-written as x += 2

There are compound statement assignment operators for all of the arithmetic operators, binary operators i.e. +=, -=,/=,%=

Increment and Decrement

++ and -- are increment and decrement operators in Java, it increments or decrements operand value by 1.

x++ can be also written as x = x + 1 x-- can also be written as x = x - 1

They are used in the below forms

  1. Postfix - In this form, operators appear after operand i.e. x++. In this form, the first current value of the operand is used in the expression then the operand value is incremented or decremented
  2. Prefix - In this form operators before operand i.e. ++x. In this form, the operand is incremented or decremented first and then used in the expression
a = 10;

b = ++a; // b is set to 11 because a is first incremented to 11 and then assigned to b 

c = 10;

d = c++; // d is set to 10 because c is first assigned to d and then value of c is incremented to 11

Example

public class ArithmeticOperators {
    public static void main(String[] args) {
        int e = 5;
        int f = 2;

        int  g = e / f;
        int  h = e % f;

        System.out.println(g); // 2
        System.out.println(h); // 1

        int x = 10;
        x += 5;

        System.out.println(x); //15

        int a = 10;
        int b = ++a;
        System.out.println(b); // 11

        int c = 10;
        int d = c++;
        System.out.println(d); // 10
    }
}

Bitwise Operators

Java provides bitwise operators that can be applied to integer types: byte, short, int, long and char. These operators act upon the individual bits of their operands in binary format.

To understand bitwise operators, we need to clearly understand how integer types are stored in binary representation.

All of the integer types (except char) are signed integers i.e. They represent positive and negative values. Java uses two's complement encoding, which means negative numbers are represented by inverting (changing 1's to 0's and vice versa) for all of bits in a value and then adding 1 to the result.

Example - Below are binary representations of 10 decimal values and how to get -10 using 2's complement.

image.png

Because Java uses two's complements to store negative numbers - and because all integers are signed values in Java - applying bitwise operators can easily produce unexpected results. It is important to remember that the high-order bit determines the sign of an integer no matter how that high-order bit gets set.

Bitwise Logical Operators

The bitwise logical operators are &, |, ^ and ~.

img-3.png

Below are truth table for these

img-4.png

Example

4 -> 0 1 0 0
2 -> 0 0 1 0 

4 & 2 -> 0 0 0 0 -> 0
4 | 2  -> 0 1 1 0 -> 6
4 ^ 2 -> 0 1 1 0 -> 6 
~4      -> 1 0 1 1 -> -5
public class BitwiseOperators {
    public static void main(String[] args) {
        byte b = 10;
        System.out.println(Integer.toBinaryString(b));//1010

        byte c = -10;
        System.out.println(Integer.toBinaryString(c)); //11110110 - ignore higher bits

        byte x = 4;
        byte y = 2;

        System.out.println(x & y); // 0
        System.out.println(x | y); // 0
        System.out.println(x ^ y); // 6
        System.out.println(~x); // -5
    }
}

Relational Operators

  1. It is used to determine equality and ordering between operands. The outcome of these operations is a Boolean value.
  2. Below are relational operators

img-5.png Image Source - javastudypoint.com/2019/12/relational-opera..

  1. Any types in Java, including integers, floating-point numbers, characters and booleans can be compared using equality test == and the inequality test !=
  2. Only numeric types (integer, floating-point and character) can be compared using ordering operators
  3. The relational operators are most frequently used in the expressions that controls if statement and the various loop statements.

Boolean Logical Operators

They operate only on Boolean operands.

img-6.png

The logical Boolean operators &, | and ^, operate on boolean values in the same way that they operate on the bits of an integer. The following table shows the effect of each logical operations -

img-7.png Image Source - java.meritcampus.com/core-java-topics/boole..

  1. Short-circuit Logical Operators OR Conditional-and and Conditional-or (&& and || )
    1. Java will not bother to evaluate the right-hand operand when outcome of the expression can be determined by the left operand alone.
    2. It is recommended to use short-circuit forms of AND and OR for boolean logic expression.
  2. The ? operator
    1. Java includes a special ternary operator (three-way) that can replace certain types of if-then-else statements.
    2. The ? has this general form: expression1 ? expression2 : expression3. Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated, otherwise expression3 is evaluated.
    3. Both expression2 and expression3 are required to return the same (or compatible) type, which can't be void.

Operator Precedence

Below are order of precedence of Java operators, from highest to lowest. Operators in the same row are equal precedence. In binary operations, the order of evaluation is left to right (except for assignment , which evaluates right to left.)

Parentheses have highest precedence as compared to below operators. Parenthesis raise the precedence of the operations that are inside them.

img-8.png Image Source - docs.oracle.com/javase/tutorial/java/nutsan..

Did you find this article valuable?

Support subodh's blog by becoming a sponsor. Any amount is appreciated!