Operators
In the Java Fundamentals lesson, we stored values in variables.
In this lesson, we’re going to learn about operators, symbols like + and > that calculate new values from existing ones.
Robot code is full of them.
Counting the balls in the hopper takes +, and checking whether the shooter is up to speed takes >.
We’ll cover four kinds of operators:
- Arithmetic operators, which do math
- Assignment operators, which update a variable’s value
- Comparison operators, which compare two values
- Logical operators, which combine
trueandfalsevalues
Arithmetic Operators
Section titled “Arithmetic Operators”Arithmetic operators do basic math on numbers:
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition: Adds two values together | 5 + 2 | 7 |
- | Subtraction: Subtracts one value from the other | 5 - 2 | 3 |
* | Multiplication: Multiplies two values together | 5 * 2 | 10 |
/ | Division: Divides one value from the other | 10 / 2 | 5 |
% | Remainder: Returns the remainder of two numbers after division | 5 % 2 | 1 |
Operators can be used anywhere you would use a number, such as when giving a variable its value. Without running the code, what value does each of these variables hold?
int totalMotors = 2 + 4;int motorsPerSide = 4 / 2;int ballsLeft = 10 - 3;Answer
totalMotorsis 6, because 2 + 4 = 6motorsPerSideis 2, because 4 / 2 = 2ballsLeftis 7, because 10 - 3 = 7
When you divide one int by another, the result is also an int, and any
decimal part is dropped, so 7 / 2 is 3, not 3.5. To get a decimal
result, at least one of the numbers must be a double. 7.0 / 2 is 3.5.
This is one reason robot code mostly uses doubles. Speeds, positions, and
voltages all need their decimal parts.
Assignment Operators
Section titled “Assignment Operators”Assignment operators give a variable a new value.
You’ve already used the simplest one, =, to set a variable’s value.
The others are shorthand for updating a variable based on its current value:
| Operator | Description | Example |
|---|---|---|
= | Assigns a value to a variable | a = 2 |
+= | Addition: Takes the current value of the variable, adds the
stated amount then assigns the result to the variable. It’s the
same as | a += 3 |
-= | Subtraction: Takes the current value of the variable, subtracts
the stated amount then assigns the result to the variable. It’s
the same as | a -= 4 |
*= | Multiplication: Takes the current value of the variable,
multiplies the stated amount then assigns the result to the
variable. It’s the same as | a *= 5 |
/= | Division: Takes the current value of the variable, divides the
stated amount then assigns the result to the variable. It’s the
same as | a /= 6 |
score += 2 does the same thing as score = score + 2, but you only write the variable’s name once.
The code is shorter, and there’s one less place to mistype the name.
Here, score starts at 10 and goes up by 2, while ballsCarried starts at 5 and goes down by 1:
int score = 10;int ballsCarried = 5;score += 2;ballsCarried -= 1;
System.out.println(score); // prints 12System.out.println(ballsCarried); // prints 4Adding or subtracting 1 comes up so often that Java has operators just for it.
++ increments a variable by adding 1 to it, and -- decrements it by subtracting 1.
You’ll see ++ in most of the loops later in this stage.
| Operator | Description | Example |
|---|---|---|
++ | Increment: adds 1 to a variable | a++ |
-- | Decrement: subtracts 1 from a variable | a-- |
Each time the robot shoots a ball, it can count the shot and remove the ball from its hopper:
int shotsFired = 6;int ballsInHopper = 7;
shotsFired++; // shotsFired is now 7!ballsInHopper--; // ballsInHopper is now 6!
System.out.println(shotsFired); // prints 7System.out.println(ballsInHopper); // prints 6Comparison Operators
Section titled “Comparison Operators”Comparison operators compare two values and give back a boolean, either true or false.
They’re how a program makes decisions, which you’ll see in the Conditionals lesson.
| Operator | Description | Example | Result |
|---|---|---|---|
== | Equal to: Checks if two values are the same | 5 == 2 | false |
!= | Not Equal: Checks if two values are not the same | 5 != 2 | true |
> | Greater than: Checks if one value is greater than the other | 5 > 2 | true |
< | Less than: Checks if one value is less than the other | 5 < 5 | false |
>= | Greater than or equal to: Checks if one value is greater than or equal to the other | 6 >= 7 | false |
<= | Less than or equal to: Checks if one value is less than or equal to the other | 6 <= 6 | true |
These work like the comparisons from math class.
Here, the robot has scored 2 balls but needs 4, so ballsScored > ballsNeeded is false:
int ballsScored = 2;int ballsNeeded = 4;System.out.println(ballsScored > ballsNeeded); // prints falseOn Strings, == checks whether two variables refer to the same object,
not whether they contain the same text. Two different Strings that both
say "Plunk" can still fail an == check. To compare the text, use the
.equals() method instead. You won’t need it in this stage, but
w3schools has more
on how it works.
= vs. ==
Section titled “= vs. ==”To check whether two values are equal, use a double equals sign, ==.
A single equals sign, =, is the assignment operator.
It sets a variable’s value and doesn’t compare anything.
Mixing them up is a common mistake. This line doesn’t compile. Java reads it as an attempt to change the number 6 into 8, which not even Java can do. The error says that the left-hand side of an assignment must be a variable:
System.out.println(6 = 8);With ==, Java compares the two values instead, and this prints false, since 6 is not equal to 8:
System.out.println(6 == 8);Logical Operators
Section titled “Logical Operators”Logical operators combine boolean values, so you can make decisions based on more than one condition at a time,
like “the robot has a ball and is lined up with the target.”
Logical operators have an order of operations, just like arithmetic ones.
! comes first, then &&, then ||. Parentheses change the order, the
same way they do in math.
| Operator | Description | Example | Result |
|---|---|---|---|
&& | And: true if both statements are true | true && true | true |
|| | Or: true if at least one statement is true | true || false | true |
! | Not: reverses. If true, then false. If false, then true | !true | false |
Here, the robot has a ball, but isn’t lined up with the target yet. Without running the code, what does each line print?
boolean hasBall = true;boolean isAligned = false;
System.out.println(hasBall && isAligned);System.out.println(hasBall || isAligned);System.out.println(!hasBall);Answer
false.&&needs both values to be true, andisAlignedis false, so the robot shouldn’t shoot yet.true.||only needs one of them, andhasBallis true.false.!flips a value, andhasBallis true.
Changing a Variable vs. Using Its Value
Section titled “Changing a Variable vs. Using Its Value”An operator on its own calculates a new value, but it doesn’t change any variables.
A variable only changes when you assign the result back to it with = or another assignment operator.
Here, totalPoints is set to the result of autoPoints + 10, so its value changes to 12:
int totalPoints = 0;int autoPoints = 2;totalPoints = autoPoints + 10;System.out.println(totalPoints); // prints 12In this example, gamePieces * 2 is calculated inside the print statement instead:
int gamePieces = 6;System.out.println(gamePieces * 2); // prints 12This prints 12, but gamePieces is still 6 afterwards.
The result of gamePieces * 2 is only used for printing, and is never assigned back to gamePieces.
You can check this by printing gamePieces again on the next line.
Operators Exercise
Section titled “Operators Exercise”Exercise
Section titled “Exercise”Now, you can dive straight into Operators.java, which you set up in the Java Fundamentals lesson!
Follow the comments and write the appropriate code to achieve the objectives.