Skip to main content

Operators

Operators are symbols used to preform data manipulation and assignment. They allow us to preform math with our variables and change what values are stored in them. Operators only work with a specific types. For examples you cant multiple a String.

Arithmetic

Arithmetic operators allow us to preform math operations with variables and numbers. Below is a list of the basic operators. You can see most operators are compatible with all number datatypes, but String is only compatible with the + operator. They should all do what you expect from your 2nd grade math class. The only thing that may be unique is the modulo operator %. This is used to calculate the remainder of dividing two numbers.

Operator Description Compatible Datatypes Example
+ Addition int, double, String
1 + 1 = 2
1.5 + 1.0 = 2.5
"MARS" + "WARS" = "MARSWARS"
- Subtraction int, double
2 - 1 = 0
2.5 - 0.5 = 2.0
* Multiplication int, double
9 * 3 = 27
15 * 0.5 = 7.5
/ Division int, double
9 / 3 = 3
8.0 / 3.0 = 2.6666
% Modulo int, double
10 % 3 = 1
8.5 % 3.0 = 2.5
Data truncation

Be careful when preforming math between and an int and a double. You can not store decimal precision data in an int datatype. Any decimal precision will be truncated.

int i = 5;
double d = 0.5;

int product = i * i; // product = 25
int product = i * d; // product = 2
double product = i * d; // product = 2.5

Assignment

You should be familiar with the = operator by now, but there are several more assignment operators that we can use in our code. Below is a table which shows most of the available assignment operators.

Operator Description Example Equivalent Expression
= Assignment
int x = 0;
// Assigns a value (right side) to a variable (left side) </td>
int x = 0;
+= Addition Assignment
int x = 1;
x += 1; // x is now 2
x = x + 1;
-= Subtraction Assignment
double x = 3.14;
x -= 0.14; // x is now 3.0
x = x - 0.14;
*= Multiplication Assignment
int x = 2;
x *= 6; // x is now 12
x = x * 6;
/= Division Assignment
int x = 9;
x /= 3; // x is now 3
x = x / 3;