Variables in Java

Introduction

In this chapter, you will learn what variables are and how to declare and use them in Java. Variables are among the most important building blocks in programming because they let you store and reuse data. If the idea feels abstract at first, we use simple metaphors—and you will deepen numeric types in Numbers.

Prerequisites

  • JDK 21 and an editor set up
  • Completed Coding Standards (naming will matter here)
  • Ability to run a small main class in IntelliJ or the terminal

What Is a Variable

A variable is a named storage location with a type. In Java, you must declare the type before (or when) you use the name.

Think of it like:

  • A labeled box with a size label: the label is the variable name (userName), the size label is the type (String), and the content is the value ("Alice").
  • A parking slot sign: the sign says what kind of vehicle may park there—Java will not let you park a String in an int slot.
java
public class VariableDemo {
    public static void main(String[] args) {
        String userName = "Alice";
        System.out.println(userName);
    }
}

Why Variables Matter

Without variables, you would repeat literal values everywhere, which makes code hard to change and easy to break.

With variables, you can:

  • Reuse values
  • Update values in one place
  • Make code easier to read
  • Build logic step by step

Tip

Memory Trick

Variable = type + name + value.
In Java, the type is part of the contract—it is checked at compile time.

Declaration and Assignment

Java uses an explicit type and = for assignment.

java
// Declare and initialize in one line
int age = 18;
String city = "New York";
double price = 9.99;
boolean isStudent = true;
char grade = 'A';

You can also declare first, then assign:

java
int score;
score = 95;

Unlike Python, you cannot write age = 18 without a type in normal local variable code—the compiler needs to know what age holds.

Use Variables in Expressions

Variables are most useful when combined.

java
public class NotebookTotal {
    public static void main(String[] args) {
        double notebookPrice = 12.5;
        int quantity = 3;
        double totalCost = notebookPrice * quantity;
        System.out.println(totalCost);
    }
}

Variables Can Change (With the Same Type)

You may assign a new value to the same variable name if the new value matches the declared type.

java
int score = 60;
score = score + 10;
System.out.println(score);  // 70

Metaphor: same box label, new content—as long as the content still fits the type (int).

java
int count = 1;
// count = "two";  // Compile error: String cannot be assigned to int

Java is statically typed: each variable has a fixed type at compile time. This differs from Python, where a name can later refer to a different type.

Primitive Types vs Reference Types (Overview)

Java has two broad categories:

CategoryExamplesBeginner mental model
Primitiveint, double, boolean, char, …Stores the value directly
ReferenceString, arrays, objects you defineStores a reference to data elsewhere

This chapter uses common types only. Full numeric ranges (byte, short, long, float) and wrapper classes are covered in Numbers. Object-oriented details come in later OOP chapters.

For now, remember:

  • int, double, boolean, char are primitives
  • String is a reference type (but easy to use like text)

Naming Rules and Best Practices

Follow Java rules and Coding Standards:

Legal rules

  • Names may contain letters, digits, _, and $ (avoid $ in your own code)
  • Must not start with a digit
  • Names are case-sensitive (age and Age are different)
  • Cannot use keywords such as class, if, for (see Keywords)

Style

  • Use meaningful camelCase names: userName, totalPrice, retryCount

Good:

java
int retryCount = 0;
String userName = "Lee";

Avoid:

java
int x = 0;
String s = "Lee";

final Variables (Constants in a Method)

When a variable should not be reassigned, use final:

java
final int MAX_ATTEMPTS = 3;
final String APP_NAME = "HelloCode";
 
// MAX_ATTEMPTS = 5;  // Compile error

For class-level constants, combine static final and UPPER_SNAKE_CASE (see coding standards).

Common Beginner Mistakes

Mistake 1: Using a Variable Before Declaring It

java
public class Broken {
    public static void main(String[] args) {
        System.out.println(userAge);  // Cannot find symbol
    }
}

Fix:

java
int userAge = 20;
System.out.println(userAge);

Mistake 2: Type Mismatch

java
int age = "18";  // Incompatible types

Fix: use the correct literal or convert intentionally (conversion details appear in later chapters):

java
int age = 18;

Mistake 3: Forgetting That Java Is Not Python

python
# Python — dynamic
x = 10
x = "ten"
java
// Java — same variable must stay int
int x = 10;
// x = "ten";  // Error

Mini Practice

Try this in your IDE:

java
public class LearningProgress {
    public static void main(String[] args) {
        String name = "Tom";
        int learningDays = 9;
        String message = name + " has studied Java for " + learningDays + " days.";
        System.out.println(message);
    }
}

Expected output:

text
Tom has studied Java for 9 days.

What’s Next

Learn how to document intent with Comments, then Operators for calculations and comparisons.

FAQ

Do variables store data directly?

Primitives store values directly in the variable. Reference types store a reference to an object; the object lives elsewhere in memory. At beginner level, String name = "Tom" behaves like “name holds text.”

Why does = not mean mathematical equality?

In Java, = is assignment. Equality testing uses == for primitives and .equals() for many objects (especially String)—covered when you study operators and strings.

Can one variable change from int to String?

No. Once int age is declared, only int values (within range) may be assigned to age.

How do I choose better variable names?

Describe purpose, not implementation noise. If a reader can guess meaning from the name, it is usually good.

Do I need to memorize every numeric type now?

No. Use int for whole numbers and double for decimals in exercises until Numbers.