Lesson 4 — Storing Data

Variables

Variables are the basic storage mechanism of every program. In Java, every variable has a declared type that the compiler enforces, preventing entire categories of bugs before your code ever runs.

What is a Variable?

A variable is a named location in memory that holds a value. Think of it like a labelled box: the label is the variable name, the box has a fixed size determined by its type, and the content is the value. When you declare a variable in Java, you tell the compiler three things: what type of data it will hold, what you want to call it, and optionally what its initial value is.

Declaring and Initialising Variables

Syntax: type variableName = value;

JAVA — Variable declarations
// Declaring without initialising (must assign before use)
String city;

// Declaring and initialising in one line
String fullName   = "Thandi Mokoena";
int    age        = 22;
double averageMark = 74.5;
boolean isEnrolled = true;
char   initial    = 'T';

// Printing variables — the + operator joins text and values
System.out.println("Learner: " + fullName);
System.out.println("Age: "     + age);
System.out.println("Mark: "    + averageMark);
System.out.println("Active: "  + isEnrolled);

Variable Naming Rules (Enforced by the Compiler)

  • May contain letters, digits, underscores, and dollar signs.
  • Must begin with a letter, underscore, or dollar sign — never a digit.
  • Cannot be a Java keyword (int, class, if, etc.).
  • Case-sensitive: age, Age, and AGE are three different variables.
JAVA — Naming rules
// Valid names
int score;
String firstName;
double _tempValue;
boolean hasCompletedOrientation;

// Invalid names (compile errors)
int 1stPlace;     // starts with a digit
String class;     // "class" is a reserved keyword
double my-value;  // hyphens not allowed in identifiers

Naming Conventions (Professional Standards)

The compiler allows int X = 5;. But professional Java code uses camelCase for variable names. A variable named x tells the next programmer nothing; numberOfLearners is self-documenting.

JAVA — Professional naming
// Poor naming — legal but unprofessional
int x = 42;
String s = "Johannesburg";
boolean b = true;

// Professional naming — same values, far more readable
int numberOfLearners = 42;
String cityName      = "Johannesburg";
boolean isActive     = true;

Constants with final

When a value should never change after it is set, mark it with final. By convention, constant names are UPPER_SNAKE_CASE. The compiler will refuse to let you reassign a final variable — catching accidental changes at compile time.

JAVA — Constants
final double VAT_RATE        = 0.15;
final int    MAX_CLASS_SIZE  = 30;
final String ORGANISATION    = "Your IT Tutor";

double price     = 1200.00;
double totalCost = price * (1 + VAT_RATE);

System.out.println("Price:     R" + price);
System.out.println("Total:     R" + totalCost);
System.out.println("Org:       " + ORGANISATION);

// VAT_RATE = 0.20;  // Compile error — cannot assign to a final variable

Multiple Assignments and Swapping

JAVA — Multiple assignment and swap
// Assign same value to multiple variables
int a, b, c;
a = b = c = 10;
System.out.println(a + " " + b + " " + c); // 10 10 10

// Swap two values (requires a temporary variable)
int x = 100;
int y = 200;
int temp = x;
x = y;
y = temp;
System.out.println("x=" + x + " y=" + y); // x=200 y=100

Practice Task

Your Turn

Declare variables for: your full name, your age, your city, your course, your average mark (with decimal), whether you own a laptop (boolean). Use meaningful camelCase names. Print each variable on its own line in a formatted way. Then declare a constant for your birth year and print how old you will be in 2030.

Common Mistakes

  • Storing a decimal in an int — the decimal part is silently truncated: int mark = 74.5; stores 74.
  • Putting quotes around a number: int age = "22"; gives a type error. Numbers are not quoted.
  • Using a variable before assigning it a value — Java's compiler will catch this: 'variable might not have been initialised'.
  • Starting a variable name with a capital letter — by convention, capitals are for classes.
  • Accidentally reassigning a final variable — the compiler will catch it, but design your constants carefully from the start.

Professional Tip

Variable naming is a form of documentation. The few extra seconds spent writing numberOfEnrolledLearners instead of n are repaid many times when you or a colleague reads the code six months later.

Mini Quiz

What does the final keyword do to a variable?