Numbers and Math

Doing arithmetic in your code

7 min read

Java can do arithmetic just like a calculator, and it uses many of the same symbols you already know from math class.

The basic math operators

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • % for remainder, also called modulo
int sum = 4 + 3;
int difference = 10 - 6;
int product = 5 * 2;
int quotient = 20 / 4;
int remainder = 7 % 2;

That last one, remainder, is worth a closer look. 7 % 2 equals 1, because 2 goes into 7 three times with 1 left over. This little operator turns out to be very useful, for example to check whether a number is even or odd.

A small trap with whole numbers

When you divide two int values, Java performs whole number division and drops anything after the decimal point. So 7 / 2 results in 3, not 3.5. If you want the decimal answer, at least one of the numbers involved needs to be a double.

double result = 7.0 / 2;
System.out.println(result);

That code would print 3.5 because 7.0 is treated as a decimal number from the start.

Updating a number quickly

It is extremely common to add one to a variable, so Java gives you a shortcut called the increment operator:

int points = 5;
points++;
System.out.println(points);

That would print 6. There is also a decrement operator, --, which subtracts one instead.

Good to know: Java follows the same order of operations you learned in math class, multiplication and division before addition and subtraction. You can always use parentheses to make the order completely clear.

Numbers and math are everywhere in real programs, from calculating a shopping total to working out how many days are left until an event, so this is a skill you will lean on constantly.

Quick check

Q1 What does the % operator calculate?

Q2 What is the result of 7 / 2 when both numbers are int values in Java?

Want to save your progress? It's free.

Create a free account