Home » Operators in Java

Operators in Java

Operators in Java

Java Operators are of prime importance in Java. Without operators we wouldn’t be able to perform logical , arithmetic calculations in our programs. Thus having operators is an integral part of a programming language.

Operator in Java are the symbols used for performing specific operations in Java.

Types of Operators in Java

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators
  9. instance of operator
operators-in-java.png

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical calculations. Java supports addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%): Returns the remainder of a division operation
public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        
        // Addition
        int sum = a + b;
        System.out.println("Sum: " + sum);
        
        // Subtraction
        int difference = a - b;
        System.out.println("Difference: " + difference);
        
        // Multiplication
        int product = a * b;
        System.out.println("Product: " + product);
        
        // Division
        int quotient = a / b;
        System.out.println("Quotient: " + quotient);
        
        // Modulus (Remainder)
        int remainder = a % b;
        System.out.println("Remainder: " + remainder);
    }
}
Java

 

2. Unary Operators

Unary Plus(+): Represents the identity of the operand.

Unary Minus(-) :Negates the value of the operand.

  • Unary plus (+)
  • Unary minus (-)
  • Increment (++)
  • Decrement (–)
public class UnaryOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = -5;
        
        // Unary plus operator (+)
        int result1 = +a;
        System.out.println("Unary plus operator (+a): " + result1);
        
        // Unary minus operator (-)
        int result2 = -a;
        System.out.println("Unary minus operator (-a): " + result2);
        
        // Increment operator (++)
        a++;
        System.out.println("After incrementing a: " + a);
        
        // Decrement operator (--)
        b--;
        System.out.println("After decrementing b: " + b);
        
        // Logical complement operator (!)
        boolean bool = true;
        boolean result3 = !bool;
        System.out.println("Logical complement operator (!bool): " + result3);
    }
}
Java

3.Assignment Operator

Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (=).

  • Simple Assignment (=)
  • Compound Assignment (e.g., +=, -=, *=, /=, %=): Performs the operation and assigns the result to the variable.
public class AssignmentOperators {
    public static void main(String[] args) {
        // Assignment operator (=)
        int a = 10;
        System.out.println("a = " + a);
        
        // Addition assignment operator (+=)
        a += 5; // Equivalent to: a = a + 5;
        System.out.println("After a += 5, a = " + a);
        
        // Subtraction assignment operator (-=)
        a -= 3; // Equivalent to: a = a - 3;
        System.out.println("After a -= 3, a = " + a);
        
        // Multiplication assignment operator (*=)
        a *= 2; // Equivalent to: a = a * 2;
        System.out.println("After a *= 2, a = " + a);
        
        // Division assignment operator (/=)
        a /= 4; // Equivalent to: a = a / 4;
        System.out.println("After a /= 4, a = " + a);
        
        // Modulus assignment operator (%=)
        a %= 3; // Equivalent to: a = a % 3;
        System.out.println("After a %= 3, a = " + a);
        
        // Bitwise AND assignment operator (&=)
        int b = 7;
        b &= 3; // Equivalent to: b = b & 3;
        System.out.println("After b &= 3, b = " + b);
        
        // Bitwise OR assignment operator (|=)
        b |= 9; // Equivalent to: b = b | 9;
        System.out.println("After b |= 9, b = " + b);
        
        // Bitwise XOR assignment operator (^=)
        b ^= 5; // Equivalent to: b = b ^ 5;
        System.out.println("After b ^= 5, b = " + b);
        
        // Left shift assignment operator (<<=)
        b <<= 2; // Equivalent to: b = b << 2;
        System.out.println("After b <<= 2, b = " + b);
        
        // Right shift assignment operator (>>=)
        b >>= 1; // Equivalent to: b = b >> 1;
        System.out.println("After b >>= 1, b = " + b);
        
        // Unsigned right shift assignment operator (>>>=)
        b >>>= 1; // Equivalent to: b = b >>> 1;
        System.out.println("After b >>>= 1, b = " + b);
    }
}
Java

4.Relational Operators

Relational operators are used to compare values and determine their relationship. They include equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=)

  • Equal to (==)
  • Not equal to (!=)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)
public class RelationalOperators {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;
        
        // Equal to (==)
        System.out.println("Is a equal to b? " + (a == b));
        
        // Not equal to (!=)
        System.out.println("Is a not equal to b? " + (a != b));
        
        // Greater than (>)
        System.out.println("Is a greater than b? " + (a > b));
        
        // Less than (<)
        System.out.println("Is a less than b? " + (a < b));
        
        // Greater than or equal to (>=)
        System.out.println("Is a greater than or equal to b? " + (a >= b));
        
        // Less than or equal to (<=)
        System.out.println("Is a less than or equal to b? " + (a <= b));
    }
}
Java

5.Logical Operators

Logical operators are used to perform logical operations on boolean values. They include logical AND (&&), logical OR (||), and logical NOT (!).

  • AND (&&)
  • OR (||)
  • NOT (!)
public class LogicalOperators {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;
        
        // Logical AND (&&)
        System.out.println("a && b: " + (a && b));
        
        // Logical OR (||)
        System.out.println("a || b: " + (a || b));
        
        // Logical NOT (!)
        System.out.println("!a: " + (!a));
        
        // Logical XOR (Exclusive OR) - Java doesn't have a built-in XOR operator, but it can be simulated using AND, OR, and NOT
        boolean xorResult = (a || b) && !(a && b);
        System.out.println("a XOR b: " + xorResult);
        
        // Short-circuit AND (&)
        // Both operands are always evaluated, even if the first operand evaluates to false.
        System.out.println("a & b: " + (a & b));
        
        // Short-circuit OR (|)
        // Both operands are always evaluated, even if the first operand evaluates to true.
        System.out.println("a | b: " + (a | b));
    }
}
Java

6. Ternary operator

The ternary operator (?:) is a concise way of expressing if-else statements. It evaluates a condition and returns one of two expressions based on the result.

(condition) ? expression1 : expression2

public class TernaryOperatorExample {
    public static void main(String[] args) {
        int number = 10;
        
        // Check if number is even or odd using ternary operator
        String result = (number % 2 == 0) ? "Even" : "Odd";
        System.out.println("Number " + number + " is " + result);
        
        // Another example: Check if a person is eligible to vote
        int age = 20;
        String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
        System.out.println("Age " + age + ": " + eligibility);
        
        // Ternary operator can also be used to assign values
        int x = 5;
        int y = (x > 0) ? 10 : 20;
        System.out.println("Value of y: " + y); // Since x is greater than 0, y will be assigned 10
        
        // Ternary operator can be nested
        int z = (x > 0) ? ((x < 10) ? 1 : 2) : 3;
        System.out.println("Value of z: " + z); // If x is greater than 0 and less than 10, z will be 1; otherwise, it will be 3
    }
}
Java

7.Bitwise Operators

Bitwise operators perform operations on individual bits of binary numbers. They include bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise complement (~), left shift (<<), and right shift (>>). 

  • AND (&)
  • OR (|)
  • XOR (^)
  • Complement (~)
  • Left Shift (<<)
  • Right Shift (>>)
  • Unsigned Right Shift (>>>)
public class BitwiseOperators {
    public static void main(String[] args) {
        int a = 5; // Binary: 101
        int b = 3; // Binary: 011
        
        // Bitwise AND (&)
        int resultAnd = a & b; // Result: 1 (Binary: 001)
        System.out.println("a & b = " + resultAnd);
        
        // Bitwise OR (|)
        int resultOr = a | b; // Result: 7 (Binary: 111)
        System.out.println("a | b = " + resultOr);
        
        // Bitwise XOR (^)
        int resultXor = a ^ b; // Result: 6 (Binary: 110)
        System.out.println("a ^ b = " + resultXor);
        
        // Bitwise NOT (~) - Unary Operator
        int resultNotA = ~a; // Result: -6 (Binary: 11111111111111111111111111111010)
        System.out.println("~a = " + resultNotA);
        
        // Left Shift (<<)
        int leftShiftResult = a << 1; // Result: 10 (Binary: 1010)
        System.out.println("a << 1 = " + leftShiftResult);
        
        // Right Shift (>>)
        int rightShiftResult = a >> 1; // Result: 2 (Binary: 10)
        System.out.println("a >> 1 = " + rightShiftResult);
        
        // Unsigned Right Shift (>>>)
        int unsignedRightShiftResult = a >>> 1; // Result: 2 (Binary: 10)
        System.out.println("a >>> 1 = " + unsignedRightShiftResult);
    }
}
Java

8.Shift Operators

Shift operator in Java, namely left shift (<<) and right shift (>>), allow for bit-level manipulation by shifting the bits of a binary number.

  1. Left Shift: <<
  2. Signed Right Shift: >>
  3. Unsigned Right Shift: >>>
public class ShiftOperatorsExample {
    public static void main(String[] args) {
        int number = 10; // Binary: 1010
        
        // Left Shift (<<) - Shifts the bits of the number to the left by specified number of positions
        int leftShiftResult = number << 2; // Shifting 'number' 2 positions to the left
        System.out.println("Left Shift Result: " + leftShiftResult); // Expected: 40 (Binary: 101000)
        
        // Right Shift (>>) - Shifts the bits of the number to the right by specified number of positions
        int rightShiftResult = number >> 1; // Shifting 'number' 1 position to the right
        System.out.println("Right Shift Result: " + rightShiftResult); // Expected: 5 (Binary: 101)
        
        // Unsigned Right Shift (>>>) - Shifts the bits of the number to the right by specified number of positions, filling the leftmost bits with zeros
        int unsignedRightShiftResult = number >>> 1; // Shifting 'number' 1 position to the right
        System.out.println("Unsigned Right Shift Result: " + unsignedRightShiftResult); // Expected: 5 (Binary: 101)
    }
}
Java

9.instanceof operator

The instance of operator in Java is used to check if an object belongs to a specific class or its subclasses. It returns true if the object is an instance of the specified class or a subclass, and false otherwise.

class Animal {}
class Dog extends Animal {}

public class InstanceOfExample {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();
        
        // Using instanceof to check if an object is an instance of a class
        System.out.println("Is 'animal' an instance of Animal? " + (animal instanceof Animal)); // true
        System.out.println("Is 'animal' an instance of Dog? " + (animal instanceof Dog)); // false
        
        System.out.println("Is 'dog' an instance of Animal? " + (dog instanceof Animal)); // true
        System.out.println("Is 'dog' an instance of Dog? " + (dog instanceof Dog)); // true
        
        // Using instanceof to check if an object is an instance of a superclass
        System.out.println("Is 'dog' an instance of Object? " + (dog instanceof Object)); // true
        
        // Using instanceof to check if an object is an instance of an interface
        System.out.println("Is 'dog' an instance of Animal interface? " + (dog instanceof Animal)); // true
    }
}
Java

Conclusion

Java operators are fundamental components of the language that enable various operations to be performed on operands. They facilitate tasks such as arithmetic calculations, logical evaluations, bitwise manipulations, and more. Understanding how to use Java operators effectively is essential for writing efficient and concise code.

Throughout this guide, we’ve explored the different types of operators available in Java, including arithmetic, assignment, relational, logical, bitwise, unary, and ternary operators. Each type serves a specific purpose and has its own syntax and behavior.

By mastering Java operators, developers gain the ability to manipulate data, control program flow, and create complex algorithms. Additionally, knowing when and how to use different operators can significantly enhance code readability, maintainability, and performance.

As you continue your journey in Java programming, remember to leverage operators wisely and consistently adhere to best practices. Regular practice and experimentation with operators will deepen your understanding and proficiency in Java development.

Frequently Asked Questions

Q1. What are operators in Java?

Ans: Operators in Java are symbols that perform operations on operands. They can be used to perform arithmetic, logical, relational, and bitwise operations.


Q2. How many types of operator are there in Java?

Ans: Java operators can be broadly classified into several categories: arithmetic operators, assignment operators, relational operators, logical operators, bitwise operators, unary operators, and ternary operator.


Q3. What are arithmetic operators in Java?

Ans: Arithmetic operators in Java are used to perform mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).


Q4. What are assignment operator in Java?

Ans: Assignment operators in Java are used to assign values to variables. Examples include =, +=, =, =, /=, and %=.


Q5. What are relational operator in Java?

Ans: Relational operators in Java are used to establish relationships between operands. They include == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).


Q6. What are logical operator in Java

Ans: Logical operators in Java are used to perform logical operations such as AND (&&), OR (||), and NOT (!). They are typically used in boolean expressions.


Q7. What are bitwise operator in Java?

Ans: Bitwise operators in Java are used to perform bitwise operations on individual bits of operands. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), right shift (>>), and unsigned right shift (>>>).


Q8. What are unary operator in Java?

Ans: Unary operators in Java operate on a single operand. Examples include unary plus (+), unary minus (), increment (++), decrement (-), and logical complement (!).


Q9. What is the ternary operator in Java?

Ans: The ternary operator (? 🙂 in Java is a shorthand for the if-else statement. It evaluates a boolean expression and returns one of two values depending on whether the expression is true or false.


Q10. How does the instanceof operator work in Java?

Ans: The instanceof operator in Java is used to test whether an object is an instance of a particular class or interface. It returns true if the object is an instance of the specified class or interface, or its subclasses/interfaces, otherwise, it returns false.