Java Fundamentals
Syntax
Section titled “Syntax”Syntax is the basic set of rules that all programs in a language must follow. It’s similar to writing. In writing, the first word in a sentence has to start with a uppercase letter or all sentence need in a period. Java’s syntax is very specific, there are different rules for how certain lines of code are written. Syntax errors are the most common sorts of errors. Whenever the syntax is mentioned, pay attention closely.
Variables
Section titled “Variables”Variables are containers that are used to store information in a program. This could be a variable that holds the temperature or a variable that holds the speed of the motor.
To make a variable, there are 5 parts:
- Data type
- Name of the variable
- Equals sign
- Value
- Semi-colon
Data Types
Section titled “Data Types”Data types refer to the type of value that our variable has. It tells our program more information about our variables such as what type of information it holds and how it can be used. Unlike some programming languages such as Python, in Java every variable must have a type. This makes your programs more reliable and helps prevent some common errors because the compiler will prevent you from using the wrong type with an error.
Some example data types that are commonly used in FRC programming are:
- int: Integer numbers that are positive or negative. int only allows numbers without decimals. Example: 12
- double: Numbers that are positive or negative. Unlike int, double allows decimals. Example: 34.1
- boolean: Either
trueorfalse. - String: Holds a sequence of characters. Denoted by double quotes (”). Example: “Hello World”
When creating a String, make sure the S is capitalized! string robotName = "Plunk" will throw an error but String robotName = "Plunk" will not.
In Java, variable names may only consist of letters, numbers, and underscores (_), but variable names cannot start with a number.
The name of the variable can be whatever you want, however, we recommend making them descriptive and easy to read.
This will make it much easier for you to understand your own code and for others to help you.
One common variable naming style is camel case, where each word is capitalized except the first.
For example, frontLeftDrive, currentTemperature, and targetPosition are all camel case.
Another common variable naming style is upper snake case, where each word is capitalized and an underscore is used in between each word.
For example: BACK_LEFT_DRIVE, and GEAR_RATIO are in upper snake case.
When programming a robot, camel case is commonly used for creating variables. Upper snake case is used for constants which are variables that are defined once and are not changed.
Java is a case-sensitive programming language! This means that uppercase and lowercase letters are treated as being two different things. For example: MotorID is different from motorID. Even though it’s spelled the same, if your variable name is MotorID then you try to reference it again but spell it as motorID, Java will see the two as different, and your code will get an error.
Creating variable names can be fun, but the names should be As mentioned, we recommend making them descriptive and easy to read
Using an intake motor as an example, here are some bad and good variable names:
| Bad | Good |
|---|---|
|
|
|
|
|
|
|
|
Semi-colons
Section titled “Semi-colons”In Java, semi-colons ; are similar to a period in a sentence.
It is what tells the compiler when a statement ends.
In most cases, not having a semi-colon at the end of a line will cause an error.
Example
Section titled “Example”Taking what we learned, the following are four variables that each use 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 tend to avoid print statements and instead have other methods of debugging code, which we will talk about in a later section. However, for this section of the course we will use print statements.
When programming, it can be useful to display information. This can be helpful for making programs that display information to the user or trying to see what speed that a motor is running. In Java, we can print information to a terminal using a print statement. A print statement in Java looks like:
System.out.println("hello!");The print statement uses information given inside the parentheses, in the previous example, it’s the String “hello!”, and prints it out to the terminal screen. When using a print statement to output text, you have to surround the text with quotes, to indicate that you want to work with that text literally. A print statement without the quotes will instead interpret the text as a variable name and attempt to print the data stored by that variable. This may cause an error if you intended to print out the text literally since the text is likely not an existing variable. However, if we are printing out the value of a variable, then we do not need quotes, as shown below.
int num = 4;System.out.println(num); // prints out the value 4Often when programming, there will be a lot of print statements that display different information.
To make it clear what’s being printed, a String can be added in front of the value and then the + sign.
This method of combining strings via the + operator is known as string concatenation.
Let’s look at an example:
double speed = 1;System.out.println("Left Motor Speed " + speed);speed is set equal to 1, this will print out Left Motor Speed 1.
Notice the space between Speed and the ".
This is done to make the print out easy to read.
System.out.println("Left Motor Speed" + speed); would print out Left Motor Speed1 which isn’t easy to read.
This can also be done using many variables.
Using an empty string, " ", a space can be added in between variables in a print statement.
Let’s look at another example:
int first = 6;double second = 2.0;
System.out.println(first + " " + second);This example will print out 6 2.0.
Java recognizes that one of the items being added is a string, and converts the items on either side to a string before combining everything.
Comments
Section titled “Comments”When programming, we use comments to write notes that explain what the code does. This helps make the code more readable for others because if they are unsure of what your code does, they can read your comments. Writing comments can also help you! Leaving comments that explain what code does can be helpful when trying to understand what your code does and when debugging.
Comments are ignored by the compiler, which also means that you can use comments to prevent code from running. In Java, there are two types of comments: single-line comments and multi-line comments.
Single-line Comments
Section titled “Single-line Comments”Single line comments begin with // and mark the rest of the line as being a comment.
For example, the code below leaves the note of “This prints out Hello World.” preceding the print statement
// This prints Hello WorldSystem.out.println("Hello World");You will also see comments placed at the end of a line like the following
System.out.println("Hello World"); // This prints Hello WorldBoth examples accomplish the same tasks and there is no difference. Whether you put your comments preceding or alongside code is up to you and what makes the most sense for your code.
Multi-line Comments
Section titled “Multi-line Comments”Multi-line Comments start with /* and end with */ The text or code that is in between the two will turn into comments.
Multi-line Comments are commonly used when you have many lines of text or need to turn a large amount of code into a comment.
For example, this is a comment with two lines of text.
/* This prints Hello WorldThis is another line */System.out.println("Hello World");Writing Comments
Section titled “Writing Comments”It’s best to use comments to explain what the code is trying to do with words, rather then just restating the code. For example, this is a useful comment because it explains what the purpose is and how it accomplishes the task.
// Calculate how long is left in the match and show it to the driversSystem.out.println(150 - matchTime);This is not a useful comment because it doesn’t tell the reader what the purpose of the code is. It just restates the code.
// Print 150 minus matchTimeSystem.out.println(150 - matchTime);There’s no need to use comments for every line of code, but if something might be confusing to someone else later (or even yourself), leave a comment!
Java Fundamentals Exercise
Section titled “Java Fundamentals Exercise”Task 1: Setup
Section titled “Task 1: Setup”Use git to clone Stage 0’s template code. This is the code you will be using for the rest of Stage 0.
git clone https://github.com/frcsoftware/Stage0-Template stage0-exercisesTask 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.