Java Operators: Performing Operations on Variables and Values
Discover the different types of operators in Java, which are essential for performing operations on variables and values. This guide focuses on arithmetic operators, highlighting their usage and importance in Java programming to manipulate numerical data effectively.
Java Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | ++x |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Assignment Operators
Assignment operators are used to assign values to variables.
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
Comparison operators are used to compare two values (or variables).
Operator | Name | Description | Example |
---|---|---|---|
== | Equal to | Checks if two operands are equal | x == y |
!= | Not equal | Checks if two operands are not equal | x != y |
> | Greater than | Checks if the left operand is greater than the right operand | x > y |
< | Less than | Checks if the left operand is less than the right operand | x < y |
>= | Greater than or equal to | Checks if the left operand is greater than or equal to the right operand | x >= y |
<= | Less than or equal to | Checks if the left operand is less than or equal to the right operand | x <= y |
Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |