Java Variables

beginner35 min

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

Naming variables

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

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: