1️⃣

4.1 Arithmetic Operators

Chapter Table of Contents

Ch. 4 Operators

Section Table of Contents

Arithmetic Operators

What are operators?

In Java, special symbols called operators allow us to do special things. In fact, you’ve already learned about an operator, the assignment operator = which lets you assign a value to a variable. The assignment operator is what we call a binary operator, because it operates on 2 things: the variable and its value.
 

Basic Math in Java

Arithmetic operators allow us to do basic math in Java, and they are binary operators. You should be familiar with the operators in the following example:
// addition int a = 5 + 1; // a has the value 6 // subtraction double b = 25.6 - 90; // b has the value of -64.4 // multiplication int c = 12 * 4; // c has the value of 48
💡
Keep in mind that these operators can be used on all of the numeric types, not just the ones used in the example.
 

Integer vs. Double Division

You may have noticed that we didn’t include division in the example above. That’s because division in Java is a little tricky — there’s actually 2 kinds of division you can do!
 
The first is integer division, which is when you divide 2 integers. The quotient is an integer with the decimals truncated, or not included. For example, if you typed in 10 / 3 into your calculator, it would give you 3.33333 (going on forever). For integer division, however, 10 / 3 is 3.
// integer division int d = 10 / 3; // d has the value of 3
 
On the other hand, double division gives you the complete result (3.3333…). Double division occurs if you divide at least 1 double with another number or vice versa.
// double division double e = 10.0 / 3; // e has the value 3.33333333...
 

Modulus

The last arithmetic operator is modulus (%), which is probably unfamiliar to you if you’ve never programmed before. Modulus gives you the remainder of a division that takes place. For example, 10 % 3 (read “ten modulo three” or “ten mod three”) equals 1, because after you divide 10 by 3, the remainder is 1.
 
It may seem weird that Java has this operator, but it actually has a lot of cool applications, such as doing unit conversions for things like money or time.
// modulus int f = 10 % 3; // f has the value 1
 

Next Section

2️⃣
4.2 Augmented Assignment Operators
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.