Java Operators Explained

Vijay PrajapatiVijay Prajapati
8 min read

What is Operator ?

An operator is a symbol that performs operations on operands—these operands can be any entities on which you wish to carry out a particular action, such as addition or subtraction.

For instance, if you desire the sum of two numbers as the output, you would employ the addition operator (+). Similarly, other operators can be used for different operations accordingly.

why we need Operator?

We rely on operators to execute various operations on data, akin to mathematical operations such as addition and subtraction. In mathematics, we use symbols like '+' for addition and '-' for subtraction to manipulate numbers. Similarly, in Java, operators serve the purpose of conducting operations and tasks on data. This data can take various forms, including numerical values, alphabetic characters, or other formats.

Types of Operators in Java?

Arithmetic Operator

  1. Addition (+): Performs addition of two values.

    • Example: int sum = 5 + 3; // sum is now 8
  2. Subtraction (-): Subtracts the right operand from the left operand.

    • Example: int difference = 10 - 4; // difference is now 6
  3. Multiplication (*): Multiplies two values.

    • Example: int product = 2 * 6; // product is now 12
  4. Division (/): Divides the left operand by the right operand.

    • Example: double quotient = 8.0 / 2.0; // quotient is now 4.0
  5. Modulus (%): Returns the remainder of the division.

    • Example: int remainder = 10 % 3; // remainder is now 1
  6. Increment (++): Increases the value of a variable by 1.

    • Example: int count = 5; count++; // count is now 6
  7. Decrement (--): Decreases the value of a variable by 1.

    • Example: int value = 8; value--; // value is now 7

Relational Operators:

  1. Equal to (==): Checks if two values are equal.

    • Example: int a = 5; int b = 5; boolean isEqual = (a == b); // isEqual is true
  2. Not equal to (!=): Checks if two values are not equal.

    • Example: int x = 7; int y = 10; boolean notEqual = (x != y); // notEqual is true
  3. Greater than (>): Checks if the left operand is greater than the right operand.

    • Example: int p = 8; int q = 4; boolean isGreaterThan = (p > q); // isGreaterThan is true
  4. Less than (<): Checks if the left operand is less than the right operand.

    • Example: int m = 3; int n = 6; boolean isLessThan = (m < n); // isLessThan is true
  5. Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.

    • Example: int num1 = 5; int num2 = 5; boolean isGreaterOrEqual = (num1 >= num2); // isGreaterOrEqual is true
  6. Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

    • Example: int value1 = 10; int value2 = 15; boolean isLessOrEqual = (value1 <= value2); // isLessOrEqual is true

Logical Operators:

  1. Logical AND (&&): Returns true if both operands are true.

    • Example: boolean condition1 = true; boolean condition2 = false; boolean result = (condition1 && condition2); // result is false
  2. Logical OR (||): Returns true if at least one operand is true.

    • Example: boolean operand1 = true; boolean operand2 = false; boolean outcome = (operand1 || operand2); // outcome is true
  3. Logical NOT (!): Returns the opposite of the operand's value.

    • Example: boolean original = true; boolean inverted = !original; // inverted is false

Assignment Operators:

  1. Assignment (=): Assigns the value on the right to the variable on the left.

    • Example: int number = 42;

      Difference between Assignment(=) and Equal to (==) operator

      In scenarios where "newValue = 50" is encountered, we are assigning the value of 50 to the variable newValue. Conversely, when using the equality operator (==), we are checking whether the value of newValue is equal to 50.

        int newValue = 50;
        if (newValue = 50) {// compilation error 
        System.out.println("This is an error");
        }
        This is what the code should look like:
        int newValue = 50;
        if (newValue == 50) {
        System.out.println("This is an error");
        }
      
  2. Add and assign (+=): Adds the right operand to the left operand and assigns the result to the left operand.

    • Example: int total = 10; total += 5; // total is now 15
  3. Subtract and assign (-=): Subtracts the right operand from the left operand and assigns the result to the left operand.

    • Example: int balance = 20; balance -= 8; // balance is now 12
  4. Multiply and assign (*=): Multiplies the left operand by the right operand and assigns the result to the left operand.

    • Example: int quantity = 4; quantity *= 3; // quantity is now 12
  5. Divide and assign (/=): Divides the left operand by the right operand and assigns the result to the left operand.

    • Example: int totalItems = 24; totalItems /= 4; // totalItems is now 6
  6. Modulus and assign (%=): Computes the modulus of the left operand divided by the right operand and assigns the result to the left operand.

    • Example: int remainder = 17; remainder %= 5; // remainder is now 2

Bitwise Operators:

  1. Bitwise AND (&): Performs a bitwise AND operation.

    • Example: int result = 5 & 3; // result is 1
  2. Bitwise OR (|): Performs a bitwise OR operation.

    Example: int result = 5 | 3; // result is 7

    it's important not to mix up the Bitwise OR (|) with the logical OR (||) operator. The Bitwise OR provides output in the form of bits. The logical OR operator results in either "true" or "false" based on the conditions being evaluated.

    Bitwise OR (|)

     int a = 5; // binary: 0101
     int b = 3; // binary: 0011
     int result = a | b; // Result: 7 (binary: 0111)
    

    logical OR (||)

     boolean x = true;
     boolean y = false;
     boolean result = x || y; // Result: true
    
  3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.

    • Example: int result = 5 ^ 3; // result is 6
  4. Bitwise NOT (~): Inverts the bits of its operand.

    • Example: int result = ~5; // result is -6
  5. Left shift (<<): Shifts the bits of the left operand to the left by the number of positions specified by the right operand.

    • Example: int result = 4 << 2; // result is 16
  6. Right shift (>>): Shifts the bits of the left operand to the right by the number of positions specified by the right operand.

    • Example: int result = 16 >> 2; // result is 4
  7. Unsigned right shift (>>>): Shifts the bits of the left operand to the right by the number of positions specified by the right operand, filling the leftmost bits with zeros.

    • Example: int result = -8 >>> 2; // result is 1073741822

Conditional Operator (Ternary Operator):

  1. Conditional ( ? : ): Provides a concise way to implement a simple if-else statement.

    • Example: int x = 5; int y = 10; int max = (x > y) ? x : y; // max is 10

Instanceof Operator:

  1. instanceof: Checks if an object is an instance of a particular class or interface.

    • Example: if (obj instanceof String) { // do something }

Type Cast Operator:

  1. Explicit Type Cast (Type): Converts a value from one data type to another.

    • Example: double d = 10.5; int i = (int) d; // i is now 10

Unary Operators:

  1. Unary plus (+): Represents positive values.

    • Example: int positiveValue = +5; // positiveValue is 5
  2. Unary minus (-): Represents negative values.

    • Example: int negativeValue = -8; // negativeValue is -8
  3. Logical NOT (!): Inverts the value of a boolean expression.

    • Example: boolean original = true; boolean inverted = !original; // inverted is false
  4. Bitwise NOT (~): Inverts the bits of its operand.

    • Example: int result = ~5; // result is -6
  5. Prefix Increment (++): Increases the value of a variable by 1 before its value is used.

    • Example: int count = 5; int incremented = ++count; // incremented is 6, count is 6
  6. Prefix Decrement (--): Decreases the value of a variable by 1 before its value is used.

    • Example: int value = 8; int decremented = --value; // decremented is 7, value is 7

Miscellaneous Operators:

  1. Conditional Operator ( ? : ): Provides a concise way to implement a simple if-else statement.

    • Example: int x = 5; int y = 10; int max = (x > y) ? x : y; // max is 10
  2. instanceof: Checks if an object is an instance of a particular class or interface.

    • Example: if (obj instanceof String) { // do something }
  3. new (Object creation): Allocates memory and creates an instance of a class.

    • Example: Object obj = new Object();
  4. [] (Array subscript): Accesses elements of an array.

    • Example: int[] numbers = {1, 2, 3}; int element = numbers[1]; // element is 2
  5. . (Member access): Accesses members of a class, such as fields or methods.

    • Example: String text = "Hello"; int length = text.length(); // length is 5

These operators are essential building blocks for various operations in Java programming. Understanding them is crucial for developing effective and efficient code.

0
Subscribe to my newsletter

Read articles from Vijay Prajapati directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vijay Prajapati
Vijay Prajapati

I'm an enthusiastic engineering graduate with a passion for a challenging career. Proficient in Java programming and blockchain technology, I'm excited to contribute to the world of engineering and technology.