Operators
Operators are symbols used to perform data manipulation and assignment. They allow us to perform math with our
variables and change what values are stored in them. Operators only work with specific types. For example, you can't
multiply a String.
Arithmetic
Arithmetic operators allow us to perform 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 | |
- | Subtraction | int, double | |
* | Multiplication | int, double | |
/ | Division | int, double | |
% | Modulo | int, double | |
Be careful when performing math between an int and a double. You cannot 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; |
+= | Addition Assignment | | x = x + 1; |
-= | Subtraction Assignment | | x = x - 0.14; |
*= | Multiplication Assignment | | x = x * 6; |
/= | Division Assignment | | x = x / 3; |