Skip to content

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 true and false values

Arithmetic operators do basic math on numbers:

OperatorDescriptionExampleResult
+Addition: Adds two values together5 + 27
-Subtraction: Subtracts one value from the other5 - 23
*Multiplication: Multiplies two values together5 * 210
/Division: Divides one value from the other10 / 25
%

Remainder: Returns the remainder of two numbers after division

5 % 21

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
  • totalMotors is 6, because 2 + 4 = 6
  • motorsPerSide is 2, because 4 / 2 = 2
  • ballsLeft is 7, because 10 - 3 = 7
Dividing Integers

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 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:

OperatorDescriptionExample
=Assigns a value to a variablea = 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 x = x + y

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 x = x - y

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 x = x * y

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 x = x / y

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 12
System.out.println(ballsCarried); // prints 4

Adding 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.

OperatorDescriptionExample
++Increment: adds 1 to a variablea++
--Decrement: subtracts 1 from a variablea--

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 7
System.out.println(ballsInHopper); // prints 6

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.

OperatorDescriptionExampleResult
==

Equal to: Checks if two values are the same

5 == 2false
!=Not Equal: Checks if two values are not the same5 != 2true
>Greater than: Checks if one value is greater than the other5 > 2true
<Less than: Checks if one value is less than the other5 < 5false
>=

Greater than or equal to: Checks if one value is greater than or equal to the other

6 >= 7false
<=

Less than or equal to: Checks if one value is less than or equal to the other

6 <= 6true

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 false
Comparing Strings

On 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.

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 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.”

Note

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.

OperatorDescriptionExampleResult
&&And: true if both statements are truetrue && truetrue
||Or: true if at least one statement is truetrue || falsetrue
!Not: reverses. If true, then false. If false, then true !truefalse

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
  1. false. && needs both values to be true, and isAligned is false, so the robot shouldn’t shoot yet.
  2. true. || only needs one of them, and hasBall is true.
  3. false. ! flips a value, and hasBall is true.

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 12

In this example, gamePieces * 2 is calculated inside the print statement instead:

int gamePieces = 6;
System.out.println(gamePieces * 2); // prints 12

This 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.

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.