Operators In Java – Explained For Programmers

Introduction To Java Operator

When we think about java operator, we can relate them to basic maths operations we learned as kids, like adding, subtracting, multiplying, and dividing numbers. Just like we use those operations to manipulate numbers, we can use similar logic to instruct computers to compare, add, subtract, and perform many other operations for us in our everyday tasks.

Operators play a crucial role in programming languages, including Java, as they allow us to perform operations on data and control the program flow.

In this blog post, we will explore the various types of operators in Java, providing explanations and practical examples.

But we first need to understand what we mean by operator and operand.

Operator and Operands

Operand: A value or variable involved in an operation.

Operator: A symbol or keyword that specifies the type of operation to be performed on operands.

1. Arithmetic Operator In Java

Arithmetic operators are used to perform basic mathematical calculations. Java supports addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Let’s see some examples:

Code Snippet:

int x = 10;
int y = 5;

int sum = x + y;       
int difference = x - y;
int product = x * y;   
int quotient = x / y;  
int remainder = x % y; 
System.out.println(sum); //System.out.println(difference);System.out.println(product);System.out.println(quotient);System.out.println(remainder);

Output:

15
5
50
2
0

2. Unary Operators In Java

a. Unary Plus (+) and Unary Minus (-):

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

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

Code:

int x = 10;
int y = -x;  System.out.println(x);System.out.println(y);

Output:

10
-10

b. Increment (++) and Decrement (–):

  • ++(Increment) : Increments the value of a variable by 1.
  • –(Decrement) : Decreases the value of a variable by 1. 

Code:

int x = 5;
x++;   int y = 10;
--y;System.out.println(x);System.out.println(y);

Output:

6
9

c. Logical Complement (!)

!(Logical Complement) : Flips the value of a boolean expression

Code:

boolean isTrue = true;
boolean isFalse = !isTrue;  // isFalse becomes false
System.out.print(isFalse);

Output:

false

d. Bitwise Complement (~):

Code:

int x = 5;
int complement = ~x;  
System.out.println(x);
System.out.println(complement);

Output:

5-6

e. Type Cast

Code:

double pi = 3.14;
int approxPi = (int) pi;  
System.out.println(approxPi);   // approxPi becomes 3 (casting from double to int)

Output:

3

By understanding and utilising these unary operators, you can perform various operations on single operands efficiently in your Java code.

3. Assignment Operator In Java

Assignment operators are used to assign values to variables. The most common assignment operator is the equal sign (=). Here’s an example:

Code:

int x = 10;
int y = 5;
x += y; // equivalent to x = x + y, resulting in x being 15System.out.println(x);

Output:

15

4. Relational Operator In Java

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 (<=). Example:

Code:

int x = 10;
int y = 5;

boolean isEqual = x == y;         // false
boolean isNotEqual = x != y;      // true
boolean isGreater = x > y;        // true
boolean isLess = x < y;           // false
boolean isGreaterOrEqual = x >= y;// true
boolean isLessOrEqual = x <= y;   // 
falseSystem.out.println(isEqual);
System.out.println(isNotEqual);
System.out.println(isGreater);
System.out.println(isLess);
System.out.println(isGreaterOrEqual);
System.out.println(isLessOrEqual);
Output:
falsetruetruefalsetruefalse

5. Logical Operator In Java

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

Code:

boolean a = true;
boolean b = false;

boolean result1 = a && b; // false
boolean result2 = a || b; // true
boolean result3 = !a;    // 
falseSystem.out.println(result1);
System.out.println(result2);
System.out.println(result3);

Output:

false
true
false

6. Ternary Operator In Java

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. Example:

Code:

int x = 10;
int y = 5;

int max = (x > y) ? x : y;
System.out.println(max);

Output:

10

7. Bitwise Operator In Java

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 (>>). Example:

Code:

int x = 5;
int y = 3;

int bitwiseAnd = x & y;   // 1
int bitwiseOr = x | y;    // 7
int bitwiseXor = x ^ y;   // 6
int bitwiseComplement = ~x;  // -6
int leftShift = x << 1;   // 10
int rightShift = x >> 1;  // 2
System.out.println(bitwiseAnd);System.out.println(bitwiseOr);System.out.println(bitwiseXor);System.out.println(bitwiseComplement);System.out.println(leftShift);System.out.println(rightShift);

Output:

1
7
6
-6
10
2

8. Shift Operators In Java

Shift operators in Java, namely left shift (<<) and right shift (>>), allow for bit-level manipulation by shifting the bits of a binary number. Here’s a concise explanation with code examples:

a. Left Shift (<<):

The left shift operator (<<) shifts the bits of a number to the left by a specified number of positions, effectively multiplying the number by 2 raised to the power of the shift amount. Example:

Code:

int x = 5;
int shifted = x << 2;  //  shifted becomes 20 (5 << 2 = 5 * 2^2)
System.out.println(shifted);

Output:

20

b. Right Shift (>>):

The right shift operator (>>) shifts the bits of a number to the right by a specified number of positions, effectively dividing the number by 2 raised to the power of the shift amount. Example:

Code:

int x = 20;
int shifted = x >> 2;  // shifted becomes 5 (20 >> 2 = 20 / 2^2)
System.out.println(shifted);

Output:

5

Shift operators are commonly used in scenarios involving bitwise operations and optimising performance when working with binary data. Understanding and utilizing these operators correctly can facilitate efficient bit-level manipulations in Java.

9. Instance Of An 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. Here’s a simplified code example:

Code:

class Vehicle { }
class Car extends Vehicle { }
class Bike extends Vehicle { }

public class Main {
    public static void main(String[] args) {
        Vehicle vehicle = new Car();
        boolean isCar = vehicle instanceof Car;      // true
        boolean isBike = vehicle instanceof Bike;    // false
        boolean isVehicle = vehicle instanceof Vehicle; // true        
System.out.println(isCar);        
System.out.println(isBike);        
System.out.println(isVehicle);
    }
}

Output:

true
false
true

In the code above, ‘isCar’ is true because the object referenced by ‘vehicle’ is an instanceof the Car class. ‘isBike’ is false because the object is not an instance of the Bike class. ‘isVehicle’  is true because the object is an instance of the Vehicle class. The instanceof an operator is used to check the object type before performing specific operations or type casting.

Leave a Reply

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