Skip to content

Java Fundamentals

Welcome to the first lesson of Stage 0! We’ll start with the rules for writing Java code, then learn how to store information in variables, display it with print statements, and explain your code with comments.

Syntax is the set of rules that all code in a programming language must follow. Think of it as grammar. English sentences start with a capital letter and end with a period, and Java code has rules like that too. Java is strict about them, and code that breaks one won’t run at all. These mistakes are called syntax errors, and they’re the most common errors you’ll run into. Pay close attention whenever this course shows you the syntax for something new.

A variable is a named container that stores a piece of information in a program. A variable might hold the temperature, the speed of a motor, or the number of balls in the hopper.

Declaring a variable, or creating it, takes five parts:

  1. The data type
  2. The name of the variable
  3. An equals sign
  4. The value
  5. A semicolon

We’ll look at each of these below.

A variable’s data type tells Java what kind of value the variable holds, and what you can do with it. Unlike some programming languages, such as Python, Java requires every variable to have a type. The compiler checks those types, so if you try to store "fast" in an int variable, you get an error before the code ever runs.

Some data types commonly used in FRC programming are:

  • int: whole numbers, positive or negative, with no decimal part. Example: 12
  • double: positive or negative numbers that can have a decimal part. Example: 34.1
  • boolean: either true or false.
  • String: a sequence of characters, surrounded by double quotes ("). Example: "Hello World"
Note

String starts with a capital S! string robotName = "Plunk"; gives an error, but String robotName = "Plunk"; doesn’t.

A variable’s name can contain letters, numbers, and underscores (_), but can’t start with a number. Beyond that, you can name it anything, as long as the name describes what the variable holds. Descriptive names make your code much easier to understand for you and for anyone helping you.

Java code uses two common naming styles:

  • Camel case, where every word is capitalized except the first, like frontLeftDrive, currentTemperature, or targetPosition. Most variables use camel case.
  • Upper snake case, where every letter is capitalized and words are separated by underscores, like BACK_LEFT_DRIVE or GEAR_RATIO. This is used for constants, which are fixed values shared by the whole program, like a gear ratio.
Case sensitivity

Java is case-sensitive, so uppercase and lowercase letters count as different characters. MotorID and motorID are two different names. If you create a variable named MotorID and then refer to it as motorID, the compiler gives you an error.

Picking names is one of the fun parts of programming, and Java will happily let you name a variable bingo. Your teammates will be less happy, though, since bingo doesn’t tell them anything about what the variable holds. Using an intake motor as an example, here are some bad and good variable names:

BadGood

f Avoid short or one letter variable names. It’s not descriptive and doesn’t make it clear what the variable is for.

frontLeftMotor Clearly describes what the variable name is for and it’s easy to read.

bingo Avoid using random words. It makes it hard to know what the variable is for.

backLeftMotor The variable name is easy to read and it’s descriptive.

motor Robots have many motors. It’s not clear what the motor is used for.

intakeMotor Adding a mechanism name makes it clear that the motor belongs to the intake.

intakeMotorForTheTopIntakeRoller This is too descriptive and the name is too long, which makes it hard to read.

intakeTopMotor The variable name is shorter but it’s easy to know what the variable is for.

In Java, a semicolon (;) marks the end of a statement, a single instruction, the same way a period ends a sentence. Java doesn’t care about whitespace, like spaces, new lines, and indentation; adding more or less of it doesn’t change what your code does. Instead, it uses semicolons to tell statements apart, so leaving one out usually causes an error.

Here are four variables, each with a different data type:

int CLIMBER_ID = 51; // an integer named CLIMBER_ID that holds the value 51
double UP_POSITION = 33.5; // a double named UP_POSITION that holds the value 33.5
boolean isFinished = false; // a boolean named isFinished that holds the value false
String autoName = "Side Auto"; // a String named autoName that holds the value "Side Auto"
Note

In FRC, we usually use other tools instead of print statements to see what our code is doing, which we’ll cover later in the course. For now, print statements are the simplest way to see what’s happening in your code.

A print statement displays information in the terminal. This is useful for showing information to whoever is running the program, or for checking what your code is doing, like how fast a motor is being told to spin. A print statement in Java looks like this:

System.out.println("hello!");

This prints the text hello! to the terminal. The quotes around "hello!" tell Java to treat it as text, exactly as written. Without the quotes, Java would treat hello! as code, and give you an error, since it isn’t a valid variable name or value.

Did you know?

Printing “Hello, World!” is a tradition for the first program anyone writes in a new language. It goes back to a 1972 tutorial by Brian Kernighan at Bell Labs, and became famous when he and Dennis Ritchie used it in their 1978 book on the C programming language. You’ll see it in the examples below, too.

To print the value of a variable, leave the quotes off and use the variable’s name:

int motorCount = 4;
System.out.println(motorCount); // prints out the value 4

When a program prints a lot of information, it helps to label each value. You can combine a String with a value using the + operator; this is called string concatenation:

double speed = 1;
System.out.println("Left Motor Speed " + speed);

This prints Left Motor Speed 1.0. Since speed is a double, it’s printed with a decimal point, even though we wrote it as 1. Notice the space at the end of "Left Motor Speed ". Without it, this would print Left Motor Speed1.0.

You can also combine several values in one print statement. Without running the code, what does this print?

int ballsScored = 6;
double batteryVoltage = 12.5;
System.out.println(ballsScored + " " + batteryVoltage);
Answer

It prints 6 12.5. Because " " is a String, Java turns the values on either side of it into text, and joins everything together, with a space in between.

A comment is a note in your code, written for people instead of the computer. Comments explain why code was written, for your teammates and for you a few weeks from now. The compiler ignores comments, which also means you can turn code into a comment to stop it from running.

Java has two kinds of comments: single-line comments and multi-line comments.

A single-line comment starts with //, and everything after it on that line is part of the comment:

// This prints Hello World
System.out.println("Hello World");

A comment can also go at the end of a line of code:

System.out.println("Hello World"); // This prints Hello World

Both examples do the same thing. Whether you put a comment before your code or next to it is up to you.

A multi-line comment starts with /* and ends with */, and everything in between is part of the comment, even across several lines. Multi-line comments are useful for longer explanations, or for turning a large block of code into a comment:

/* This prints Hello World
This is another line */
System.out.println("Hello World");

A good comment explains why the code exists, instead of restating what it does. This comment is useful, because it explains the code’s purpose:

// Calculate how long is left in the match and show it to the drivers
System.out.println(150 - matchTime);

This comment isn’t useful, because it only repeats what the code already says:

// Print 150 minus matchTime
System.out.println(150 - matchTime);

You don’t need a comment on every line of code. But if something might be confusing to someone else, or to you later, leave a comment!

In this stage, you will write code based on the instructions provided in each exercise. After writing the code, you will want to run it to make sure it works. To run your code, click the arrow button in the top right corner of VS Code.

Any information that gets displayed will appear in the terminal, which is located in the Panel.

Note

When running robot code in later stages, you’ll use the WPILib Command Palette instead of the Run button. We will cover these steps in Stage 1 when you write your first robot program.

Exercise

Fork, then clone, the Stage 0 Template.

If you need help setting up a repository, read the Forking and Cloning guide.

Now, you can dive straight into Print.java! Follow the comments and write the appropriate code to achieve the objectives.