Java Operators

Operators in Java are special symbols used to perform operations on variables and values. They are fundamental to programming and allow you to manipulate data, perform calculations, and make decisions.

Key Topics

1. Arithmetic Operators

Arithmetic operators perform basic mathematical operations like addition, subtraction, multiplication, etc.

Operator Operation Example
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulusa % b
++Increment++a or a++
--Decrement--a or a--

Example

public class ArithmeticExample {
    public static void main(String[] args) {
        int a = 15;
        int b = 4;
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    }
}

Output:

a + b = 19
a - b = 11
a * b = 60
a / b = 3
a % b = 3

2. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Operation Equivalent To
=Assignmenta = b
+=Add and Assigna = a + b
-=Subtract and Assigna = a - b
*=Multiply and Assigna = a * b
/=Divide and Assigna = a / b
%=Modulus and Assigna = a % b

Example

public class AssignmentExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        a += b; // a = a + b
        System.out.println("a += b: " + a);
        a -= b; // a = a - b
        System.out.println("a -= b: " + a);
        a *= b; // a = a * b
        System.out.println("a *= b: " + a);
        a /= b; // a = a / b
        System.out.println("a /= b: " + a);
        a %= b; // a = a % b
        System.out.println("a %= b: " + a);
    }
}

Output:

a += b: 15
a -= b: 10
a *= b: 50
a /= b: 10
a %= b: 0

3. Comparison Operators

Comparison operators compare two values and return a boolean result (true or false).

Operator Operation Example
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

Example

public class ComparisonExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("a == b: " + (a == b));
        System.out.println("a != b: " + (a != b));
        System.out.println("a > b: " + (a > b));
        System.out.println("a < b: " + (a < b));
        System.out.println("a >= b: " + (a >= b));
        System.out.println("a <= b: " + (a <= b));
    }
}

Output:

a == b: false
a != b: true
a > b: false
a < b: true
a >= b: false
a <= b: true

4. Logical Operators

Logical operators are used to combine multiple boolean expressions.

Operator Operation Description
&&Logical ANDTrue if both operands are true
||Logical ORTrue if at least one operand is true
!Logical NOTInverts the boolean value

Example

public class LogicalExample {
    public static void main(String[] args) {
        boolean hasLicense = true;
        boolean hasCar = false;
        if (hasLicense && hasCar) {
            System.out.println("You can drive.");
        } else {
            System.out.println("You cannot drive.");
        }
        if (hasLicense || hasCar) {
            System.out.println("You have either a license or a car.");
        } else {
            System.out.println("You have neither a license nor a car.");
        }
        System.out.println("!hasCar: " + !hasCar);
    }
}

Output:

You cannot drive.
You have either a license or a car.
!hasCar: true

5. Bitwise Operators

Bitwise operators perform operations on individual bits of integer values.

Operator Operation Description
&Bitwise ANDEach bit of the output is 1 if the corresponding bits of both operands are 1
|Bitwise OREach bit of the output is 1 if at least one corresponding bit of either operand is 1
^Bitwise XOREach bit of the output is 1 if corresponding bits of the operands are different
~Bitwise ComplementInverts each bit
<<Left ShiftShifts bits to the left, filling with zeros
>>Right ShiftShifts bits to the right, filling with sign bit

Example

public class BitwiseExample {
    public static void main(String[] args) {
        int a = 5; // 0101 in binary
        int b = 3; // 0011 in binary
        System.out.println("a & b: " + (a & b)); // 0001 in binary
        System.out.println("a | b: " + (a | b)); // 0111 in binary
        System.out.println("a ^ b: " + (a ^ b)); // 0110 in binary
        System.out.println("~a: " + (~a)); // 1010 in binary (two's complement)
        System.out.println("a << 1: " + (a << 1)); // 1010 in binary
        System.out.println("a >> 1: " + (a >> 1)); // 0010 in binary
    }
}

Output:

a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2

6. Other Operators

Java includes some special operators for specific tasks.

  • Ternary Operator: A shorthand for if-else statements. Syntax: condition ? expression1 : expression2
  • Instanceof Operator: Checks if an object is an instance of a specific class or interface.

6.1 Ternary Operator Example

public class TernaryExample {
    public static void main(String[] args) {
        int score = 85;
        String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
        System.out.println("Your grade is: " + grade);
    }
}

Output:

Your grade is: B

6.2 Instanceof Operator Example

public class InstanceofExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        boolean result = str instanceof String;
        System.out.println("Is str an instance of String? " + result);
    }
}

Output:

Is str an instance of String? true

Key Takeaways

  • Operators are essential tools for manipulating data and controlling program flow.
  • Understanding different types of operators helps write efficient and effective code.
  • Practice using operators to become proficient in Java programming.