Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the +
operator to add together two values:
Example
int a = 100 + 50;
Java divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | a + b |
- | Subtraction | Subtracts one value from another | a - b |
* | Multiplications | Multiplies two values | a * b |
/ | Division | Divides one value by another | a / b |
% | Modulus | Returns the division remainder | a % b |
++ | Increment | Decreases the value of a variable by 1 | ++a |
Assignment Operators
Assignment operators are used in Java to assign values to variables.
There are several different assignment operators in Java. The most basic assignment operator is the equals (=) sign.
Operator | Description | Example |
---|---|---|
= | Simple assignment operator | a=2 |
+= | Add and assignment operator | a+=2 |
-= | Subtract and assignment operator | a-=2 |
*= | Multiply and assignment operator | a*=2 |
/= | Divide and assignment operator | a/=2 |
++ | Modulus and assignment operator | a%=2 |
<<= | Shift left and assignment operator | a<<=2 |
>>= | Shift right and assignment operator | a>>=2 |
>>>= | Unsigned shift right and assignment operator | a>>>=2 |
&= | Bitwise AND and assignment operator | a&=2 |
^= | Bitwise XOR and assignment operator | a^=2 |
Logical Operators
Logical operators in Java are used to combine multiple conditional statements. There are three types of logical operators in Java:
- AND operator (&&)
- OR operator (||)
- NOT operator (!)
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | a < 5 && a < 10 |
|| | Logical or | Returns true if one of the statements is true | a < 5 || a < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(a < 5 && a < 10) |