AI Hints
Home›Java Tutorial›double and float, Arithmetic, Division and Remainder
Java · Lesson 15 of 120

Division and Remainder

Surprises with whole numbers.

⏱ 2 min read▶ Video at 19:17🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Division in Java has one big surprise. When you divide two whole numbers, the answer is a whole number too. The decimal part is simply thrown away.

  • int / int
  • Gives an int
  • Decimals are dropped

Whole number division

Seventeen divided by five, both whole numbers. The percent sign gives the remainder, what's left over. If either number is a decimal, Java does decimal division. Run it. Seventeen over five is just three! The remainder is two. And with a decimal, we get three point four.

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.println(17 / 5);
        System.out.println(17 % 5);
        System.out.println(17.0 / 5);
        System.out.println(17 / 5.0);
    }
}
Output
3
2
3.4
3.4

Using the remainder

The remainder is surprisingly useful. One hundred and thirty five minutes, divided by sixty, gives the hours. The remainder gives the minutes left over. And a number is even, when the remainder after dividing by two is zero. Run it. Two hours, fifteen minutes. And fourteen is even, true.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int minutes = 135;
        int hours = minutes / 60;
        int left = minutes % 60;
        System.out.println(minutes + " minutes = " + hours + "h " + left + "m");

        int n = 14;
        System.out.println(n + " is even? " + (n % 2 == 0));
    }
}
Output
135 minutes = 2h 15m
14 is even? true

Remember

Int divided by int gives an int. To get decimals, make one side a double. Percent gives the remainder. And dividing an int by zero crashes your program.

keyvalue
17 / 53
17.0 / 53.4
17 % 52
x / 0crash: ArithmeticException

Summary

Whole number division drops the decimals. The percent sign gives the remainder. Next, characters, and true or false.

Key takeaways
  • int / int → int
  • % remainder
  • Even: n % 2 == 0
Next up: char and boolean — letters and yes or no