Java Operators
Operators are symbols that do work on values, like adding numbers or comparing them.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division | 7 / 3 | 2 |
% | Remainder (modulus) | 7 % 3 | 1 |
++ | Increment | x++ | adds 1 |
-- | Decrement | x-- | subtracts 1 |
Example
java
public class Main {
public static void main(String[] args) {
int total = 1250;
int people = 4;
System.out.println(total / people);
System.out.println(total % people);
System.out.println(total / 4.0);
}
}Output
312 2 312.5
When both numbers are int, Java does integer division and drops the decimal part. Make one of them a double (like 4.0) to get the exact answer.
Assignment Operators
| Operator | Same as |
|---|---|
x = 5 | put 5 in x |
x += 3 | x = x + 3 |
x -= 3 | x = x - 3 |
x *= 3 | x = x * 3 |
x /= 3 | x = x / 3 |
Example
java
public class Main {
public static void main(String[] args) {
int balance = 1000;
balance += 500; // salary arrives
balance -= 200; // mobile load
balance++; // one rupee bonus
System.out.println(balance);
}
}Output
1301
Comparison Operators
Comparison operators give a boolean answer: true or false.
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
Logical Operators
Logical operators combine conditions:
&&(and): true only if both sides are true||(or): true if at least one side is true!(not): flips true to false and false to true
Example
java
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasCnic = true;
System.out.println(age >= 18);
System.out.println(age >= 18 && hasCnic);
System.out.println(age < 18 || !hasCnic);
}
}Output
true true false
Order of Operations
Java follows normal maths rules: *, / and % happen before + and -. Use brackets to make the order clear:
Example
java
int a = 2 + 3 * 4; // 14
int b = (2 + 3) * 4; // 20Exercise
Exercise
What is the value of 17 % 5 in Java?
