Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Arithmetic Operators | Variables and Data Types
Introduction to Java

Arithmetic Operators

Swipe to show menu

Now that you understand variables and data types, you can start doing something more interesting with them — math operations.

In Java, we use five main arithmetic operators:

  • + — addition;
  • - — subtraction;
  • * — multiplication;
  • / — division;
  • % — modulus (remainder).

Example Code

Here’s a simple example using all five operators in a coffee shop scenario:

Main.java

Main.java

12345678910111213141516171819202122232425262728293031
package com.example; public class Main { public static void main(String[] args) { int coffeeCupsSold = 35; int coffeeCupsInStock = 120; int coffeeCupPrice = 5; // Addition int total = coffeeCupsInStock + coffeeCupsSold; // Subtraction int remaining = coffeeCupsInStock - coffeeCupsSold; // Multiplication int revenue = coffeeCupPrice * coffeeCupsSold; // Division int days = coffeeCupsInStock / coffeeCupsSold; // Modulus int leftover = coffeeCupsInStock % coffeeCupsSold; System.out.println(total); System.out.println(remaining); System.out.println(revenue); System.out.println(days); System.out.println(leftover); } }

The example declares three variables: coffeeCupsSold, coffeeCupsInStock, and coffeeCupPrice to represent our coffee shop data. Then we apply all five arithmetic operators to calculate totals, remaining stock, revenue, how many days stock will last, and the leftover cups after dividing evenly. Finally, each result is printed to the screen using System.out.println().

question mark

What does the modulus operator % return?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 5
some-alt