Java Operators Cheat Sheet & Practice Tasks
1. Arithmetic Operators in Java
Arithmetic operators perform basic mathematical operations.
| Operator | Meaning | Example | Result |
|----------|-------------------|-----------|--------|
|+ | Addition |5+2 |7 |
|- | Subtraction |5-2 |3 |
|* | Multiplication |5*2 | 10 |
|/ | Division | 10 / 2 |5 |
|% | Modulus | 10 % 3 |1 |
Division with integers in Java cuts off decimals (e.g. 5 / 2 = 2).
Example Code:
int a = 12, b = 5;
System.out.println("Addition: " + (a + b)); // 17
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 60
System.out.println("Division: " + (a / b)); // 2
System.out.println("Modulus: " + (a % b)); // 2
Micro-Tasks: Arithmetic Operators
1. Write a program to calculate the area and perimeter of a rectangle.
- area = length * width
- perimeter = 2 * (length + width)
2. Create a calculator that asks for two numbers and prints their:
- Sum, Difference, Product, Quotient, and Remainder.
3. Ask the user for minutes and convert it to:
Java Operators Cheat Sheet & Practice Tasks
- Hours (integer division), Remaining minutes (modulus).
2. Comparative Operators in Java
Comparative operators compare two values and return true or false.
| Operator | Meaning | Example | Result |
|----------|--------------------------|-----------|--------|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 4 | true |
|> | Greater than |7>2 | true |
|< | Less than |3<5 | true |
| >= | Greater than or equal to | 6 >= 6 | true |
| <= | Less than or equal to | 8 <= 9 | true |
Example Code:
int x = 8, y = 10;
System.out.println("x == y: " + (x == y)); // false
System.out.println("x != y: " + (x != y)); // true
System.out.println("x > y: " + (x > y)); // false
System.out.println("x < y: " + (x < y)); // true
System.out.println("x >= y: " + (x >= y)); // false
System.out.println("x <= y: " + (x <= y)); // true
Micro-Tasks: Comparative Operators
1. Compare two ages:
- Are they the same?
- Who is older or younger?
2. Write a grading checker:
- 75+: "Distinction"
Java Operators Cheat Sheet & Practice Tasks
- 50-74: "Pass"
- Below 50: "Fail"
3. Create a login check:
- Compare user input to saved username and password.
- Print success or failure.