CodeBlanks Logo Icon CodeBlanks

Arithmetic

Learn +, -, *, /, % operators.

Arithmetic operators

Java has five arithmetic operators: +, -, *, /, %. The first four do the usual four operations; % is the modulo (remainder) operator.

int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1 (remainder)

Integer division gives an integer result: 10 / 3 = 3. For a decimal result, at least one side must be double: 10.0 / 3 = 3.333....

Integer vs decimal division

When you divide two ints, Java gives the result as an integer, dropping the fraction. For a decimal result, at least one side must be double.

System.out.println(7 / 2);      // 3
System.out.println(7.0 / 2);    // 3.5
System.out.println(7 / 2.0);    // 3.5

If one side of the division is double, Java automatically widens the other side to double too. This is widening conversion.

Knowing which type to use matters: double for averages, int for counting.

Practice Write arithmetic calculations

Write a Main class with a main method. Assign 20 to int a and 6 to int b. Print a + b, a / b and a % b on separate lines with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int a = 20;
        int b = 6;
        System.out.println(a + b);
        System.out.println(a / b);
        System.out.println(a % b);
    }
}

Expected output

26
3
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the result of 10 % 3?

  • 10
  • 3
  • 0
  • 1 Correct answer

Explanation: 10 % 3 = 1, because 10 = 3*3 + 1.

2 Complete the modulo operator

Question
int remainder = 10 ____ 3;
Answer
int remainder = 10 % 3;

Explanation: 10 % 3 gives the remainder.

3 Match the operators

Term Meaning
+ Addition
- Subtraction
* Multiplication
% Remainder

All lessons in Beginner