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
Section titled “Syntax”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.
Variables
Section titled “Variables”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:
- The data type
- The name of the variable
- An equals sign
- The value
- A semicolon
We’ll look at each of these below.
Data Types
Section titled “Data Types”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:12double: positive or negative numbers that can have a decimal part. Example:34.1boolean: eithertrueorfalse.String: a sequence of characters, surrounded by double quotes ("). Example:"Hello World"
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, ortargetPosition. Most variables use camel case. - Upper snake case, where every letter is capitalized and words are separated by underscores, like
BACK_LEFT_DRIVEorGEAR_RATIO. This is used for constants, which are fixed values shared by the whole program, like a gear ratio.
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:
| Bad | Good |
|---|---|
|
|
|
|
|
|
|
|
Semicolons
Section titled “Semicolons”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.
Putting It Together
Section titled “Putting It Together”Here are four variables, each with a different data type:
int CLIMBER_ID = 51; // an integer named CLIMBER_ID that holds the value 51double UP_POSITION = 33.5; // a double named UP_POSITION that holds the value 33.5boolean isFinished = false; // a boolean named isFinished that holds the value falseString autoName = "Side Auto"; // a String named autoName that holds the value "Side Auto"Print Statements
Section titled “Print Statements”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.
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 4Combining Text and Values
Section titled “Combining Text and Values”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.
Comments
Section titled “Comments”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.
Single-Line Comments
Section titled “Single-Line Comments”A single-line comment starts with //, and everything after it on that line is part of the comment:
// This prints Hello WorldSystem.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 WorldBoth examples do the same thing. Whether you put a comment before your code or next to it is up to you.
Multi-Line Comments
Section titled “Multi-Line Comments”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 WorldThis is another line */System.out.println("Hello World");Writing Useful Comments
Section titled “Writing Useful Comments”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 driversSystem.out.println(150 - matchTime);This comment isn’t useful, because it only repeats what the code already says:
// Print 150 minus matchTimeSystem.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!
Running code
Section titled “Running code”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.
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.
Java Fundamentals Exercise
Section titled “Java Fundamentals Exercise”Task 1: Setup
Section titled “Task 1: Setup”Fork, then clone, the Stage 0 Template.
If you need help setting up a repository, read the Forking and Cloning guide.
Task 2: Exercises
Section titled “Task 2: Exercises”Now, you can dive straight into Print.java!
Follow the comments and write the appropriate code to achieve the objectives.