Operators Overview

  1. Addition (+): Adds two operands.
    • Examplesum = 3 + 2; // sum is 5
  2. Subtraction (-): Subtracts the right operand from the left operand.
    • Exampledifference = 5 - 3; // difference is 2
  3. Multiplication (*): Multiplies two operands.
    • Exampleproduct = 4 * 2; // product is 8
  4. Division (/): Divides the left operand by the right operand.
    • Examplequotient = 10 / 2; // quotient is 5
  5. Modulus (%): Returns the remainder of division of the left operand by the right operand.
    • Exampleremainder = 10 % 3; // remainder is 1
  6. Logical AND (&): Performs a logical AND operation on each bit; true if both operands are true.
    • Exampleresult = true & 1; // result is true (true AND true)
  7. Logical OR (|): Performs a logical OR operation on each bit; true if at least one operand is true.
    • Exampleresult = false | 0; // result is false (true OR false)
  8. Logical XOR (^): Performs a logical XOR operation on each bit; true if operands are different.
    • Exampleresult = 1 ^ 0; // result is true (true XOR false)
  9. Assignment (=): Assigns the value of the right operand to the left operand.
    • Examplea = 5.3; // a is assigned the value 5.3
  10. Not Equal (!=): Returns true if the operands are not equal.
    • ExampleisNotEqual = (5 != 3); // isNotEqual is true
  11. Less Than (<): Returns true if the left operand is less than the right operand.
    • ExampleisLess = (3 < 5); // isLess is true
  12. Greater Than (>): Returns true if the left operand is greater than the right operand.
    • ExampleisGreater = (7 > 4); // isGreater is true
  13. Equal (==): Returns true if the operands are equal.
    • ExampleisEqual = (5 == 5); // isEqual is true
  14. Less Than or Equal To (<=): Returns true if the left operand is less than or equal to the right operand.
    • ExampleisLessOrEqual = (3 <= 5); // isLessOrEqual is true
  15. Greater Than or Equal To (>=): Returns true if the left operand is greater than or equal to the right operand.
    • ExampleisGreaterOrEqual = (7 >= 4); // isGreaterOrEqual is true

Compound Assignments

Arithmetic operators (+, -, *, /, %) can be combined with the assignment operator (=) to update a variable’s value directly after performing the operation. This is known as compound assignment:

  • Addition Assignment (+=)a += b is equivalent to a = a + b.
  • Subtraction Assignment (-=)a -= b is equivalent to a = a - b.
  • Multiplication Assignment (*=)a *= b is equivalent to a = a * b.
  • Division Assignment (/=)a /= b is equivalent to a = a / b.
  • Modulus Assignment (%=)a %= b is equivalent to a = a % b.

These operators provide a shorthand way to update variables, making code more concise and potentially improving readability.