Do Some Math
Perform basic math operations in Java and print results.
We'll cover the following
Now let’s turn Java into your personal calculator. You’ll use arithmetic operators to do math and instantly see the results.
Goal
You’ll aim to:
Perform basic math operations.
Use
System.out.println()
with numbers.Store results in variables.
Add and subtract
Let’s start by adding and subtracting two numbers. Java will do the math and print the results:
public class Main {public static void main(String[] args) {System.out.println(10 + 5); // 15System.out.println(10 - 3); // 7}}
Java evaluates the math before printing it.
Nice work! You just made Java do the math for you.
Multiply and divide
Let’s try multiplying and dividing two numbers to see the results:
public class Main {public static void main(String[] args) {System.out.println(6 * 4); // 24System.out.println(20 / 5); // 4}}
When you divide integers in Java, you only get the whole number part of the answer—no decimals.
Great job! You’ve successfully multiplied and divided the numbers and printed the results!
%
Modulo (Remainder)
Let’s try the modulo of two numbers to see the results:
public class Main {public static void main(String[] args) {System.out.println(10 % 3); // 1}}
%
gives you the remainder.
Great job! You’ve successfully printed the remainder.
Arithmetic Operator | Operation | Example |
| Addition | 10 + 5 results in 15 |
| Subtraction | 10 - 5 results in 5 |
| Multiplication | 10 * 5 results in 50 |
| Division | 10 / 5 results in 2 |