Operators are symbols or keywords to perform a specific operation.
Assignment operator (=)
Often used for assigning variables to a value.
variable = value;
Using an integer variable integer,
int integer = 8;Arithmetic operators
| operator | description | expression |
|---|---|---|
| + | addition | a + b |
| - | subtraction | a - b |
| * | multiplication | a * b |
| / | division | a / b |
| % | modulo | a % b |
Keynote of modulo operator: a % b returns the remainder of the expression. For example, if a is 4 and b is 3, it returns a remainder of 1 |
Compound assignment
They perform an arithmetic operation on the current value of the variable. It’s a shortcut to modify the variable itself without referencing it again.
| expression | equivalent to… |
|---|---|
y += x; | y = y + x; |
x -= 5; | x = x - 5; |
x /= y; | x = x / y; |
price *= units + 1; | price = price * (units+1); |
Increment and decrement (++, —)
variable++ or variable --
Only works for integer variables
These expressions increase or decrease the value of the same variable by one.
++x;
// Other similarities
x += 1;
x = x + 1;Relational and comparison operators
These expressions are compared or related using the relational/comparison operators. For instance, if you were to compare the difference of two values, you’d use greater (>) or less than operator (<).
| operator | description | examples |
|---|---|---|
| == | Equal to | (7 == 5) // evaluates to false |
!= | Not equal to | (5 != 4) // evaluates to true |
< | Less than | (3 < 2) // evaluates to false |
> | Greater than | (6 > 6) // evaluates to true |
<= | Less than or equal to | (5 <= 10) // evaluates to true |
>= | Greater than or equal to | (8 >= 5) // evaluates to true |
Expression of the variables in comparison works too in the evaluation.
(a == 5) // evaluates to false, since a is not equal to 5
(a*b >= c) // evaluates to true, since (2*3 >= 6) is true
(b+4 > a*c) // evaluates to false, since (3+4 > 2*6) is false
((b=2) == a) // evaluates to true Logical operators (!, &&, ||)
The ! operator makes the boolean expression opposite (or NOT the expression) similar to inverting a value. For example, !true is the opposite of true, which is false.
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true
!(6 <= 4) // evaluates to true because (6 <= 4) would be false
!true // evaluates to false
!false // evaluates to true The && logical operator is an AND operator that requires two expressions or more to be true. For example,
(true && true) // Evaluates true
((5==5) && (4*8 == 32)) // Evaluates true
((12*4 == 36) && (6 < 4)) // Evaluates falseOn the other hand, || only requires at least one expression to be true. For example,
(true || false) // Evaluates true
((9 < 32) || ("oof" == "oof")) // Evaluates true
((12*4 == 36) || (8/4 == 1)) // Evaluates true