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*

<aside> 💡 Keep in mind that these operators can be used on all of the numeric types, not just the ones used in the example.

</aside>

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.