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
12345678910111213141516171819202122232425262728293031package 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().
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 5
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 2. Chapter 5