Operators in Java

Operators are symbols that perform operations on variables and values. Java supports several types of operators:

Relational (Comparison) Operators

These are used to compare two values. The result is a boolean (true or false).

OperatorOperatorExample
==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
Output
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false
Arithmetic Operators

These are used to perform basic arithmetic operations.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division15 / 3 = 5
%Modulus (remainder)5 % 3 = 2
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
Logical Operators

These are used to perform logical operations on boolean expressions.

OperatorDescriptionExample
||Logical ORcondition1 || condition2
&&Logical ANDa && b
!Logical NOT!a
Output
a && b: false
a || b: true
!a: false
Assignment Operators

These are used to assign values to variables.

OperatorDescriptionExample
=Assigna = 10
+= Add and assigna += 5 (same as a = a + 5)
-=Subtract and assigna -= 3
*=Multiply and assigna *= 2
/=Divide and assigna /= 2
Output
a += 5: 15
a -= 3: 12
a *= 2: 24
a /= 2: 12

Bitwise AND (&) and Bitwise OR (|) Operators in Java

The bitwise operators in Java allow you to manipulate individual bits of data types like integers and bytes. Bitwise operations are different from logical operators (&&, ||) because they operate directly on the binary representations of integers rather than evaluating boolean expressions.

Bitwise AND (&)

The bitwise AND operator (&) performs a binary AND operation on two integer values, comparing each bit of the two integers. The result is a binary value where a bit is set to 1 only if both corresponding bits in the two operands are 1. If either bit is 0, the resulting bit is 0.

Syntax:

result = operand1 & operand2;
Bitwise AND Operation:
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

Explanation:

  • a = 6 is 0110 in binary.
  • b = 3 is 0011 in binary.
  • Performing 0110 & 0011 results in 0010, which is 2 in decimal.
0110  (6 in binary)
&
0011  (3 in binary)
------
0010  (Result = 2)
Bitwise OR (|)

The bitwise OR operator (|) performs a binary OR operation on two integer values, comparing each bit of the two operands. The result is a binary value where a bit is set to 1 if either of the corresponding bits in the two operands is 1. If both bits are 0, the resulting bit is 0.

Syntax:

result = operand1 | operand2;
Bitwise OR Operation:
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

Explanation:

  • a = 6 is 0110 in binary.
  • b = 3 is 0011 in binary.
  • Performing 0110 | 0011 results in 0111, which is 7 in decimal.
0110  (6 in binary)
|
0011  (3 in binary)
------
0111  (Result = 7)