Operators are special symbols or keywords that perform operations on one or more operands. They are fundamental to programming, allowing you to manipulate data and control program flow. This section delves into the various types of operators available and their usage.
These operators are used to perform mathematical calculations:
Operator | Description | Example |
---|---|---|
+ |
Addition | int sum = 10 + 5; |
- |
Subtraction | int difference = 10 - 5; |
* |
Multiplication | int product = 10 * 5; |
/ |
Division | int quotient = 10 / 5; |
% |
Modulo (Remainder) | int remainder = 10 % 3; |
++ |
Increment | x++; (equivalent to x = x + 1; ) |
-- |
Decrement | x--; (equivalent to x = x - 1; ) |
These operators compare two values and return a boolean result (true
or false
):
Operator | Description | Example |
---|---|---|
== |
Equal to | if (a == b) { ... } |
!= |
Not equal to | if (a != b) { ... } |
> |
Greater than | if (a > b) { ... } |
< |
Less than | if (a < b) { ... } |
>= |
Greater than or equal to | if (a >= b) { ... } |
<= |
Less than or equal to | if (a <= b) { ... } |
These operators combine boolean expressions:
Operator | Description | Example |
---|---|---|
&& |
Logical AND | if (condition1 && condition2) { ... } |
|| |
Logical OR | if (condition1 || condition2) { ... } |
! |
Logical NOT | if (!condition) { ... } |
These operators assign values to variables:
Operator | Description | Example |
---|---|---|
= |
Assign | x = 5; |
+= |
Add and assign | x += 3; (equivalent to x = x + 3; ) |
-= |
Subtract and assign | x -= 3; (equivalent to x = x - 3; ) |
*= |
Multiply and assign | x *= 3; (equivalent to x = x * 3; ) |
/= |
Divide and assign | x /= 3; (equivalent to x = x / 3; ) |
%= |
Modulo and assign | x %= 3; (equivalent to x = x % 3; ) |
These operators perform operations on individual bits of their operands.
(Detailed explanation of Bitwise Operators will be covered in an advanced topic.)
There are several other operators, including:
?:
): A shorthand for an if-else
statement.+
): Used to join strings.Understanding the correct usage and precedence of operators is crucial for writing efficient and error-free code.