Java Variables
What variables are
A variable is a named place in memory that holds one value. You pick a type (such as int or String), give it a name, and read or update it as the program runs.
Key ideas
- Declaration: Choose a type and a name.
- Initialization: Set the first value, often in the same line as declaration.
- Assignment: Replace the value later with
=. - Scope: The region of code where the name is legal to use.
Basic variable example
// Declaration and initialization
int age = 16;
String name = "Robot";
double speed = 12.5;
boolean isActive = true;
// Using variables
System.out.println("Robot name: " + name);
System.out.println("Age: " + age + " months");
System.out.println("Speed: " + speed + " mph");Naming variables
Good Practices:
- Use descriptive names:
motorSpeedinstead ofms - Start with lowercase letter:
robotName - Use camelCase for multiple words:
maxBatteryLevel - Constants in UPPER_CASE:
MAX_SPEED
Avoid:
- Starting with numbers:
2wheels - Using Java keywords:
class,public - Special characters (except _ and $):
robot-name - Single letters (except for loop counters):
x,y
Variable scope example
public class Robot {
// Class-level variable (can be used anywhere in the class)
private String robotName = "FRC Bot";
public void startRobot() {
// Method-level variable (only used in this method)
int startupTime = 5;
if (startupTime > 0) {
// Block-level variable (only used in this if block)
String message = "Starting up...";
System.out.println(message);
}
// 'message' cannot be used here - out of scope!
}
}Try It Yourself:
Exercise 1: Create Variables
- A String for the robot’s team name
- An integer for the number of wheels
- A double for the robot’s weight in pounds
- A boolean to track if the robot is autonomous
Create variables for a robot's properties: