Java Arithmetic: Doing Math with Code
Now that you know how to store data in variables, it’s time to make your program do some work. In Java, we use Arithmetic Operators to perform math, ranging from simple addition to finding remainders.
1. The Basic Five
Java uses standard symbols for most operations. If you've used a calculator, these will look very familiar.
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds two values together | 5 + 2 = 7 |
- |
Subtraction | Subtracts one value from another | 5 - 2 = 3 |
* |
Multiplication | Multiplies two values | 5 * 2 = 10 |
/ |
Division | Divides one value by another | 10 / 2 = 5 |
% |
Modulo | Finds the remainder after division | 5 % 2 = 1 |
2. The Modulo Operator (%)
The Modulo operator is often new to beginners. It doesn't give you the result of a division; it gives you what is left over.
- Example: If you have 10 cookies and share them between 3 friends, everyone gets 3 cookies, and 1 is left over.
- In Java:
10 % 3equals1.
Real-world use: We often use % to check if a number is even or odd. If number % 2 is 0, the number is even!
3. The "Integer Division" Trap
In Java, if you divide two whole numbers (int), the result must be a whole number. Java will simply chop off the decimal part.
int result = 5 / 2;
System.out.println(result); // Output: 2 (The .5 is deleted!)
The Fix: If you want an accurate decimal result, at least one of the numbers must be a double.
double accurateResult = 5.0 / 2;
System.out.println(accurateResult); // Output: 2.5
💻 Code Example: A Simple Bill Splitter
Copy this code to see how operators work together:
public class MathFun {
public static void main(String[] args) {
double totalBill = 54.50;
int people = 4;
// Addition and Division
double tax = 5.50;
double finalTotal = totalBill + tax;
double perPerson = finalTotal / people;
System.out.printf("Total with tax: $%.2f %n", finalTotal);
System.out.printf("Each person pays: $%.2f %n", perPerson);
// Modulo example
int items = 11;
int boxes = 3;
int remaining = items % boxes;
System.out.println("Remaining items after boxing: " + remaining);
}
}
4. Order of Operations
Java follows the standard math rules (PEMDAS/BODMAS). It calculates in this order:
- Parentheses
() - Multiplication
*, Division/, and Modulo%(Left to right) - Addition
+and Subtraction-(Left to right)
int math = 5 + 2 * 10; // Result: 25
int math2 = (5 + 2) * 10; // Result: 70
💡 Challenge: Temperature Converter
Write a program that asks the user for a temperature in Fahrenheit and converts it to Celsius.
- Formula:
Celsius = (Fahrenheit - 32) * 5 / 9 - Hint: Use
doublefor your variables to keep the decimals accurate!