Unit 2: Java Basics
Operators are the special symbols that perform operations on your variables and values. They are the verbs of programming, allowing you to do everything from basic math to complex logical comparisons.
In Java, operators are the building blocks for any computation or decision-making in your code. They can be grouped into several key categories, each with a specific purpose. Let's explore the most common ones you'll use in FRC.
These are the operators used for basic mathematical calculations. They work just like they do in algebra.
// FRC Example: Calculating total points int autoPoints = 15; int teleopPoints = 30; int totalScore = autoPoints + teleopPoints; // totalScore is 45 // FRC Example: Finding the remainder int totalGamePieces = 10; int piecesPerCycle = 3; int piecesLeftOver = totalGamePieces % piecesPerCycle; // piecesLeftOver is 1
Be careful when dividing two integers. Java performs integer division, which truncates (chops off) any decimal part. For example, 10 / 3 will result in 3, not 3.333. To get a decimal result, at least one of the numbers must be a double: 10.0 / 3.
Assignment operators are used to assign values to variables. The basic assignment operator is =. Java also provides compound assignment operators that combine an arithmetic operation with assignment for more concise code.
// FRC Example: Incrementing a score counter int score = 0; score += 5; // score is now 5 score += 10; // score is now 15 // FRC Example: Reducing motor power double motorSpeed = 1.0; motorSpeed -= 0.25; // motorSpeed is now 0.75
These operators compare two values and return a boolean result (either true or false). They are the foundation of all `if` statements and conditional logic.
// FRC Example: Checking if an arm has reached its target double targetAngle = 90.0; double currentAngle = 90.1; boolean atTarget = (currentAngle >= targetAngle); // atTarget is true // FRC Example: Checking if we are on the red alliance String alliance = "Red"; boolean isRed = (alliance == "Red"); // isRed is true
Logical operators are used to combine multiple boolean expressions into a single result. They are essential for creating complex conditions in your code.
// FRC Example: Checking if it's safe to shoot boolean shooterAtSpeed = true; boolean turretIsAimed = false; // Using AND: both must be true boolean readyToShoot = shooterAtSpeed && turretIsAimed; // readyToShoot is false // Using OR: only one needs to be true boolean isEnabled = true; boolean inAuto = false; boolean isRobotActive = isEnabled || inAuto; // isRobotActive is true // Using NOT boolean hasGamePiece = false; boolean needsToRunIntake = !hasGamePiece; // needsToRunIntake is true
Question: You want to run the intake motor only if the robot is enabled AND the driver is pressing the 'A' button. Which logical operator would you use to combine these two conditions?