Java Variables — Declaring, Initializing & Naming Rules

4 minute read

In the previous chapter, we printed a fixed message. But real programs need to store and manipulate data — that’s what variables are for.


What Is a Variable?

A variable is a named container that holds a value in your computer’s memory.

Think of it like a labeled box:

┌───────────┐    ┌───────────┐    ┌───────────┐
│   age     │    │   name    │    │  isActive │
│    25     │    │  "Alice"  │    │   true    │
└───────────┘    └───────────┘    └───────────┘
   (int)          (String)         (boolean)

Each box has:

  • A name (the label — age, name, isActive)
  • A type (what kind of data it holds — int, String, boolean)
  • A value (the data stored inside — 25, "Alice", true)

Declaring a Variable

In Java, you must declare a variable before using it. Declaration tells Java the type and name:

int age;          // Declare an integer variable named 'age'
String name;      // Declare a String variable named 'name'
boolean isActive; // Declare a boolean variable named 'isActive'

At this point, the variables exist but don’t have a value yet (they’re empty boxes).


Initializing a Variable

Initialization means giving a variable its first value:

age = 25;
name = "Alice";
isActive = true;

You can declare and initialize in one line (this is most common):

int age = 25;
String name = "Alice";
boolean isActive = true;

Complete Example

public class VariableDemo {
    public static void main(String[] args) {
        // Declare and initialize
        String name = "Alice";
        int age = 25;
        double salary = 75000.50;
        boolean isEmployed = true;

        // Print the values
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Salary: $" + salary);
        System.out.println("Employed: " + isEmployed);
    }
}

Output:

Name: Alice
Age: 25
Salary: $75000.5
Employed: true

Changing a Variable’s Value

Variables can be reassigned (that’s why they’re called “variable” — their value can vary):

int score = 100;
System.out.println(score);  // 100

score = 200;                // Reassign
System.out.println(score);  // 200

score = score + 50;         // Use current value to calculate new value
System.out.println(score);  // 250

Output:

100
200
250

The var Keyword (Java 10+)

Since Java 10, you can use var for local variables — Java infers the type from the value:

var name = "Alice";     // Java knows this is a String
var age = 25;           // Java knows this is an int
var price = 9.99;       // Java knows this is a double
var active = true;      // Java knows this is a boolean

Note: var only works for local variables (inside methods). You can’t use it for class fields.

// This does NOT work:
var x;  // Error! Java can't infer the type without a value

Constants with final

If a variable should never change, declare it with final:

final double PI = 3.14159;
final String APP_NAME = "MyApp";
final int MAX_RETRIES = 3;

// PI = 3.0;  // Compile error! Cannot reassign a final variable

Convention: constants use UPPER_SNAKE_CASE.


Naming Rules and Conventions

Rules (enforced by the compiler)

Rule Example Invalid
Must start with a letter, $, or _ age, $price, _count 1age ❌
Can contain letters, digits, $, _ age2, user_name user-name ❌
Cannot be a reserved word score ✅ int ❌, class ❌
Case-sensitive age ≠ Age ≠ AGE —

Conventions (followed by all Java developers)

Convention Usage Example
camelCase Variables and methods firstName, totalScore
PascalCase Classes HelloWorld, StudentRecord
UPPER_SNAKE_CASE Constants MAX_SIZE, PI
// ✅ Good variable names
int studentAge = 20;
String firstName = "Alice";
double accountBalance = 1500.75;
boolean isLoggedIn = false;

// ❌ Bad variable names
int x = 20;        // What does 'x' mean?
String s = "Alice"; // What does 's' hold?
double d = 1500.75; // Meaningless

Multiple Variables on One Line

You can declare multiple variables of the same type on one line:

int x = 1, y = 2, z = 3;

But don’t — it’s harder to read. Prefer one variable per line:

int x = 1;
int y = 2;
int z = 3;

Common Mistakes

Mistake 1: Using a Variable Before Declaring It

System.out.println(score);  // Error! 'score' doesn't exist yet
int score = 100;

Mistake 2: Using a Local Variable Without Initializing

int age;
System.out.println(age);  // Error! Variable 'age' might not have been initialized

Mistake 3: Wrong Type Assignment

int age = "twenty-five";  // Error! Can't put a String into an int

Try It Yourself

Write a program PersonInfo.java that:

  1. Creates variables for a person’s name, age, height (in meters), and whether they’re a student
  2. Prints all the information in a formatted way

Expected output:

Name: Bob
Age: 22
Height: 1.78 meters
Student: true

Summary

Concept Key Point
Variable Named container for data in memory
Declaration int age; — create the container
Initialization age = 25; — put data in
Both at once int age = 25; (most common)
var Local type inference (Java 10+)
final Makes a variable a constant
Naming camelCase for variables, meaningful names

What’s Next?

Now that you know how to create variables, let’s learn about all the types of data Java can store:

Java Data Types →

Updated: