Operators
Do math, compare values, and make decisions! A complete guide to Java operators.
Do math, compare values, and make decisions! A complete guide to Java operators. This hands-on tutorial focuses on practical implementation of operators concepts.
Operators
Operators are symbols that perform operations on variables and values.
1. Arithmetic Operators
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 by 1 | ++x |
-- | Decrement | Decreases the value by 1 | --x |
2. Comparison Operators
Used to compare two values. Returns a boolean.
| 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 |
3. Logical Operators
Used to combine conditional statements.
| 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) |
4. Assignment Operators
Used to assign values to variables.
=, +=, -=, *=, /=, %=.
Example: x += 3 is same as x = x + 3.
5. Bitwise Operators
Used to perform manipulation of individual bits of a number.
& (AND), | (OR), ^ (XOR), ~ (Complement), << (Left Shift), >> (Right Shift).
6. Type Comparison Operator
instanceof compares an object to a specified type.
String str = "Hello";
boolean result = str instanceof String; // true
7. Ternary Operator
Ideally a shorthand for if-else.
variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
String result = (time < 18) ? "Good day" : "Good evening";
Interactive Code
Test your math skills!
[!TIP] Notice that
10 / 3prints3, not3.33. This is because both are integers. To get a decimal, cast one todouble:(double) a / b.
AI Mentor
Confused about "Java arithmetic, logical and comparison operators details"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4What is the result of 10 % 3?
Next Steps
Now that we can manipulate data, let's learn how to control the flow of our program with Control Flow Statements (if-else, loops).