Page Content

Tutorials

What are the Operators in Java? & What is Operator and type?

Operators in Java

Operators are unique symbols in Java that apply particular operations to one, two, or three operands before returning a result. These operators are essential for creating expressions and working with variables.

Operators in Java

The following describes the various kinds of Java operators:

Arithmetic Operators

Like algebraic operators, arithmetic operators are employed in mathematical computations. Any numeric data type can use them, as can char types because char is regarded as a subset of int.

The fundamental arithmetic operators consist of:

  1. + (Addition):  Adding values on either side is done with the + symbol. String concatenation is another application for it.
  2. – (Subtraction):  The right operand is subtracted from the left using the operator -.
  3. * (Multiplication):  Values are multiplied on both sides by * (multiplication).
  4. / (Division): The left operand is divided by the right operand using the operator / (Division). Any remainder is trimmed when dividing an integer.
  5. % (Modulus): To find the remainder, divide one operand by another using the formula % (modulus). Both floating-point and integer types can use this.

Code Example (ArithmeticDemo):

class ArithmeticDemo {
    public static void main (String[] args) {
        int result = 1 + 2;         // result is now 3
        System.out.println("1 + 2 = " + result);
        int original_result = result;
        result = result - 1;        // result is now 2
        System.out.println(original_result + " - 1 = " + result);
        original_result = result;
        result = result * 2;        // result is now 4
        System.out.println(original_result + " * 2 = " + result);
        original_result = result;
        result = result / 2;        // result is now 2
        System.out.println(original_result + " / 2 = " + result);
        original_result = result;
        result = result + 8;        // result is now 10
        System.out.println(original_result + " + 8 = " + result);
        original_result = result;
        result = result % 7;        // result is now 3
        System.out.println(original_result + " % 7 = " + result);
    }
}

Output:

1 + 2 = 3
3 - 1 = 2
2 * 2 = 4
4 / 2 = 2
2 + 8 = 10
10 % 7 = 3

Relational Operators

Finding the equality and ordering of two operands is accomplished through the use of relational operators. These operations produce a boolean value as their result.

The following are important relational operators:

  • == (Equal to): Checks if the values of two operands are equal. It’s crucial to remember to use == for comparison, not = (which is for assignment).
  • != (Not equal to): Checks if the values of two operands are not equal.
  • > (Greater than): Checks if the left operand’s value is greater than the right’s.
  • < (Less than): Checks if the left operand’s value is less than the right’s.
  • >= (Greater than or equal to):.
  • <= (Less than or equal to):.

All number kinds and char can be used with these operators. But you can only compare boolean values for equality or inequality, not for ordering (for example, true > false is meaningless).

Code Example (ComparisonDemo):

class ComparisonDemo {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if(value1 == value2)
            System.out.println("value1 == value2");
        if(value1 != value2)
            System.out.println("value1 != value2");
        if(value1 > value2)
            System.out.println("value1 > value2");
        if(value1 < value2)
            System.out.println("value1 < value2");
        if(value1 <= value2)
            System.out.println("value1 <= value2");
    }
}

Output:

value1 != value2
value1 < value2
value1 <= value2

Logical Operators

Boolean expressions can be combined or a boolean operand’s logical state inverted using logical operators. Additionally, a boolean value is the outcome of a logical operation.

Common logical operators consist of:

  1. & (Logical AND): Returns true if both operands are true.
  2. | (Logical OR): Returns true if at least one operand is true.
  3. ^ (Logical XOR – Exclusive OR): Returns true if exactly one operand is true.
  4. ! (Logical NOT): Inverts the boolean value of its operand.

Short-Circuit Logical Operators (&& and ||): Java offers unique short-circuit syntax for AND and OR operators, which can result in code that is more efficient.

  • && (Conditional-AND): Only when necessary is the second operand evaluated using the && (Conditional-AND) operator. In an AND operation, the second operand is not processed if the first operand is false because the overall result is false regardless of the second operand.
  • || (Conditional-OR): In the case of conditional-OR, the second operand is evaluated only when necessary. When the first operand of an OR operation is true, the second operand is not evaluated because the overall result is true regardless of the second operand.

Code Example (ConditionalDemo1):

class ConditionalDemo1 {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}

Output:

value1 is 1 AND value2 is 2
value1 is 1 OR value2 is 1

Assignment Operators

By using the straightforward assignment operator (=), the value of the right operand is transferred to the left operand.

Shorthand assignment operators, which combine an assignment with an arithmetic or bitwise operation, are another feature of Java. The formal name for this is compound assignment operators. For example, x = x + 10; can be written as x += 10;.. Any Java binary operator can be used with this shortcut.

Among the compound assignment operators are:

  1. += (Add and assign)
  2. -= (Subtract and assign)
  3. *= (Multiply and assign)
  4. /= (Divide and assign)
  5. %= (Modulus and assign)

These compound operators can be more effective and are more compact.

Code Example (OpEquals):

class OpEquals {
    public static void main(String args[]) {
        int a = 1;
        int b = 2;
        int c = 3;
        a += 5;
        b *= 4;
        c += a * b;
        c %= 6;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
    }
}

Output:

a = 6
b = 8
c = 3

Increment/Decrement Operators

The value of their operand is increased by one for the increment (++) operator and decreased by one for the decrement (--) operator.

They are useful in two ways:

  • Prefix form (++x or –x): The operation is carried out prior to the operand’s value being used in the expression in prefix form (++x or –x).
  • Postfix form (x++ or x–): The expression uses the operand’s original value before the action is carried out (x++ or x–).

Code Example (PrePostDemo):

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++; // i becomes 4
        System.out.println(i); // prints 4
        ++i; // i becomes 5
        System.out.println(i); // prints 5
        System.out.println(++i); // i becomes 6, then prints 6
        System.out.println(i++); // prints 6, then i becomes 7
        System.out.println(i); // prints 7
    }
}

Output:

4
5
6
6
7

Bitwise Operators

Bitwise operators are applied to integral types (like long, int, short, char, and byte) and perform operations on the individual bits of their operands. They cannot be used on boolean, float, double, or class types.

Bitwise operators that are often used include:

  1. ~ (Bitwise unary NOT / Complement): Inverts all bits of its operand.
  2. & (Bitwise AND): If the corresponding bits of both operands are 1, then this produces a 1 bit. utilized frequently to “turn bits off” or verify whether a bit is set.
  3. | (Bitwise OR): Generates a 1 bit if at least one of the corresponding bits of the operands is 1. The ability to “turn bits on”
  4. ^ (Bitwise exclusive OR – XOR): If exactly one of the operands’ corresponding bits is 1, the operation yields a 1 bit; if not, it yields a 0. possesses a feature that is helpful for encoding: when a value is XORed twice with the same key, the original value is restored.

Bit Shift Operators

  • << (Signed left shift): Shifts bits to the left using \< (Signed left shift). Zeros are inserted into empty spaces on the right. The value doubles with every left shift.
  • >> (Signed right shift): The symbol for “right shift” is >>, which moves bits to the right. By replicating the sign bit (left-most bit), empty spaces on the left are filled while maintaining the sign.
  • >>> (Unsigned right shift): Regardless of the sign bit, the empty spaces on the left are always filled with zeros. Since a left shift inherently fills with zeros, a “signed” left shift is unnecessary, hence there is no <<<.

Code Example (BitDemo):

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F; // Binary 0000 0000 0000 1111
        int val = 0x2222;     // Binary 0010 0010 0010 0010
        // (val & bitmask) performs bitwise AND:
        //   0010 0010 0010 0010
        // & 0000 0000 0000 1111
        // --------------------
        //   0000 0000 0000 0010 (Decimal 2)
        System.out.println(val & bitmask); // prints "2"
    }
}

Output:

2
Index