Operators in Java

Operators are special symbols in Java that perform operations on variables and values. They are essential in expressions, calculations, comparisons, and logical decisions.

Here’s a complete breakdown:


🔑 1. Arithmetic Operators

Used for mathematical calculations.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division10 / 2 = 5
%Modulus (remainder)10 % 3 = 1
++Incrementi++ or ++i
--Decrementi-- or --i
int a = 5, b = 3;
System.out.println(a + b); // 8
System.out.println(a % b); // 2

🔑 2. Relational Operators

Used for comparison, return true or false.

OperatorDescriptionExample
==Equal toa == b
!=Not equala != b
>Greater thana > b
<Less thana < b
>=Greater or equala >= b
<=Less or equala <= b
int x = 10, y = 20;
System.out.println(x < y); // true
System.out.println(x == y); // false

🔑 3. Logical Operators

Used to combine boolean expressions.

OperatorDescriptionExample
&&AND → true if both true(x>0 && y>0)
``
!NOT → inverts boolean!(x>0)
boolean a = true, b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a);     // false

🔑 4. Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Simple assignmenta = 10
+=Add and assigna += 5a = a + 5
-=Subtract and assigna -= 5
*=Multiply and assigna *= 5
/=Divide and assigna /= 5
%=Modulus and assigna %= 5

🔑 5. Bitwise Operators

Operate on binary representation of integers.

OperatorDescriptionExample
&AND5 & 3 = 1
``OR
^XOR5 ^ 3 = 6
~NOT~5 = -6
<<Left shift5 << 1 = 10
>>Right shift5 >> 1 = 2
>>>Unsigned right shift-5 >>> 1 = large positive

public class BitwiseExample {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011

    System.out.println("a & b = " + (a & b)); // 0101 & 0011 = 0001 → 1
    System.out.println("a | b = " + (a | b)); // 0101 | 0011 = 0111 → 7
    System.out.println("a ^ b = " + (a ^ b)); // 0101 ^ 0011 = 0110 → 6
    System.out.println("~a = " + (~a));       // ~0101 = 1010 (in 2’s complement → -6)
    System.out.println("a << 1 = " + (a << 1)); // 0101 << 1 = 1010 → 10
    System.out.println("a >> 1 = " + (a >> 1)); // 0101 >> 1 = 0010 → 2
    System.out.println("-a >>> 1 = " + (-a >>> 1)); // Unsigned shift
}

}

🔑 6. Ternary Operator

  • Shortcut for if-else statements.
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max = " + max);

🔑 7. Instanceof Operator

  • Checks if an object is an instance of a class or subclass.
String s = "Hello";
System.out.println(s instanceof String); // true

✅ Summary

  • Arithmetic+ - * / % ++ --
  • Relational== != > < >= <=
  • Logical&& || !
  • Assignment= += -= *= /= %=
  • Bitwise& | ^ ~ << >> >>>
  • Ternarycondition ? value1 : value2
  • Instanceof → checks object type

Leave a Reply