Operators in Java are employed to execute operations on variables and values.
In the following example, we utilize the + operator to sum two values:
|
While the + operator is commonly employed to sum two values as demonstrated above,
it can also combine a variable with a value or another variable.
int
|
In Java, operators are categorized into the following groups:
Arithmetic operators facilitate common mathematical operations.
Operator |
Name |
Description |
Example |
|
+ |
Addition |
Performs addition on two values |
x + y |
|
– |
Subtraction |
Performs subtraction by deducting one value from another. |
x – y |
|
* |
Multiplication |
Performs multiplication by multiplying two values together. |
x * y |
|
/ |
Division |
Performs division by dividing one value by another. |
x / y |
|
% |
Modulus |
Calculates the remainder after division. |
x % y |
|
++ |
Increment |
Increments the value of a variable by 1. |
++x |
|
— |
Decrement |
Decrement the value of a variable by 1 |
–x |
Assignment operators are employed to assign values to variables.
In the following example, the assignment operator (=) is used to assign the value 10 to a variable named x:
|
The addition assignment operator (+=) adds a value to a variable and assigns the result back to the variable.
|
A comprehensive list of all assignment operators:
Operator |
Example |
Same As |
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x – 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
&= |
x &= 3 |
x = x & 3 |
|= |
x |= 3 |
x = x | 3 |
^= |
x ^= 3 |
x = x ^ 3 |
>>= |
x >>= 3 |
x = x >> 3 |
<<= |
x <<= 3 |
x = x << 3 |
Comparison operators are utilized to compare two values or variables. This aspect is crucial in programming as it aids in finding solutions and making decisions.
The outcome of a comparison operation is either true or false, known as Boolean values. You’ll delve deeper into these concepts in the Booleans and If..Else chapter.
In this example, we utilize the greater than operator (>) to determine if 5 is greater than 3.
|
Operator | Name | Example |
== | Equal to | x==y |
!= | Not equal | x!=y |
> | Greater than | x>y |
< | Less than | x<y |
>= | Greater than or equal to | x>=y |
<= | Less than or equal to | x<=y |
You can also assess true or false conditions using logical operators.
Logical operators help establish the logical relationship between variables or values.
Operator |
Name |
Description |
Example |
&& |
Logical and |
Returns true if both conditions are true |
x < 5 && x < 10 |
|| |
Logical or |
Returns true if any one of the condition is true |
x < 5 || x < 4 |
! |
Logical not |
Reverses the result, returning false if the original result is true |
!(x < 5 && x < 10) |