Java Variables

What are Variables?

Variables in Java are containers that store data values. Think of them as labeled boxes where you can keep different types of information that your program can use and modify.

Key Concepts:

  • Declaration: Creating a variable with a specific type
  • Initialization: Giving the variable its first value
  • Assignment: Changing the variable's value
  • Scope: Where in your code the variable can be used

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");

Variable Naming Rules:

Good Practices:
  • Use descriptive names: motorSpeed instead of ms
  • 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:

Open full interactive app