Lesson 5 — Operators
A simple intro to Java
Just like with variables, there are a few different kinds of operators. These operators also follow the rules of order of operations. You can also add parenthesis to change the order, just like in arithmetic.
As you would imagine, this one adds things together.
int add = 1 + 1; // add = 2
And this one subtracts!
int sub = 1–1; // sub = 0
This one multiplies.
int multi = 3 * 2; // multi = 6
And this one divides. Notice how the decimal gets dropped because the answer is being put into an int data type, which doesn’t handle decimals.
int div = 7 / 2; // div = 3 // 7 ÷ 2 = 3.5
This is called the mod sign. This one gives you the remainder of a division problem.
int remain = 7 / 2; // remain 1 // 7 ÷ 2 = 3 Remainder 1
Sometimes when you are using a for loop or just doing simple arithmetic, you have to add or subtract one. There’s an easy way to do that.
int add = 1;
add++; //add = 2
int sub = 1;
sub --; //sub = 0
The basic operator is the equal sign. As you saw above, you can just use it to assign some data to a variable.
sub = 3;
You can also quickly add, subtract, multiply or divide things to themselves.
int add = 0;
add += 5; //add = 5
// same thing as saying: add = add + 5;
int sub = 0;
sub -= 5; //add = -5
// same thing as saying: sub = sub — 5;
int multi = 2;
multi *= 3; //add = 6
// same thing as saying: multi = multi * 3;
int div = 7;
div /= 2; //add = 3
// same thing as saying: div = div / 2;
Conversion and Casting
Since all of these data types have different amounts that they can hold, then we have to be careful moving in-between them. Moving up the chain and putting a smaller type into a bigger type will not give you any errors. However, when you try to move down the chain, you will get errors.
The way to avoid these errors is by casting the data into the appropriate type. You can cast data by putting the type you want in parenthesis right after the equal sign.
int i = 1;
double d = 1.123;
i = (int) d; // i = 1
b = (byte) d; // b = 1
You can also do this win you are moving up the chain, but you don’t have to because the computer automatically does it for you.
Have questions? Ask them below!