LearnContact
Lesson 755 min read

Variables in Java

Learn how Java variables store data, including declaration, initialization, assignment, scope, lifetime, local variables, instance variables, static variables, type inference, naming rules, default values, and common mistakes.

Introduction

Programs work with data. A shopping application stores product prices, a banking application stores account balances, a game stores player scores, and a student management system stores names, ages, and grades.

Variables allow Java programs to store, access, and modify data while the program is running. Almost every useful Java application uses variables.

In the previous lesson, you learned how a Java program is structured. You saw fields, local variables, method parameters, and static members. In this lesson, you will study variables in detail.

Simple Variables
String name = "Alex";

int age = 21;

double salary = 45000.50;

boolean active = true;
Variable Concept
VARIABLE

┌──────────────────────┐
│                      │
│      STORED VALUE    │
│                      │
└──────────────────────┘

        ▲
        │
        │
   VARIABLE NAME
What You Will Learn
  • What a variable is.
  • Why programs need variables.
  • How variables store data.
  • How to declare variables.
  • How to initialize variables.
  • How to assign values.
  • How to reassign values.
  • How to declare multiple variables.
  • How to copy values between variables.
  • How variables are used in expressions.
  • The three main categories of variables in Java.
  • What local variables are.
  • What instance variables are.
  • What static variables are.
  • The differences between local, instance, and static variables.
  • What variable scope means.
  • How block scope works.
  • How method scope works.
  • How parameter scope works.
  • How class-level scope works.
  • How nested scopes work.
  • What variable lifetime means.
  • The lifetime of local variables.
  • The lifetime of instance variables.
  • The lifetime of static variables.
  • Which variables receive default values.
  • Why local variables must be initialized before use.
  • The difference between primitive and reference variables.
  • How local variable type inference works with var.
  • Where var can and cannot be used.
  • Java variable naming rules.
  • Java variable naming conventions.
  • Why Java variable names are case-sensitive.
  • Why reserved words cannot be used as variable names.
  • How variable shadowing occurs.
  • How this distinguishes fields from local variables.
  • How method parameters behave as variables.
  • A simplified view of variables in memory.
  • The basic relationship between stack and heap memory.
  • How variable values change.
  • How to swap variable values.
  • Why temporary variables are useful.
  • Common variable errors and how to avoid them.

What is a Variable?

A variable is a named storage location used to hold a value that a program can access.

Variable Example
int age = 21;
Variable Breakdown
int age = 21;
 │   │     │
 │   │     └── Value
 │   │
 │   └──────── Variable Name
 │
 └──────────── Data Type

In this example, int is the data type, age is the variable name, and 21 is the value stored in the variable.

Conceptual View
VARIABLE NAME

age

        │
        ▼

┌──────────────┐
│      21      │
└──────────────┘

STORED VALUE

Why Variables are Needed

Without variables, programs would have difficulty storing information that changes while the application runs.

Without a Variable
System.out.println(100 + 50);

System.out.println(100 - 20);
With a Variable
int balance = 100;

System.out.println(balance + 50);

System.out.println(balance - 20);

Store Data

Variables hold values that the program needs.

Change Data

Variable values can be updated while the program runs.

Perform Calculations

Variables can participate in mathematical and logical expressions.

Store Input

User input can be stored in variables.

Produce Output

Stored values can be displayed or returned.

Maintain State

Variables help applications remember current information.

Real-World Analogy

A variable can be compared to a labeled container. The label identifies the container, while the content represents the stored value.

Container Analogy
LABEL: age

┌──────────────────┐
│                  │
│        21        │
│                  │
└──────────────────┘


LABEL: name

┌──────────────────┐
│                  │
│      "Alex"      │
│                  │
└──────────────────┘

The variable name acts like the label. The variable type determines what kind of value the variable can hold.

Variable Structure

General Syntax
dataType variableName = value;
Structure
dataType variableName = value;
    │          │        │
    │          │        └── Initial Value
    │          │
    │          └─────────── Variable Name
    │
    └────────────────────── Data Type
Examples
int age = 21;

double price = 99.99;

char grade = 'A';

boolean active = true;

String name = "Alex";

Variable Declaration

Variable declaration introduces a variable by specifying its type and name.

Declaration
int age;
Declaration Breakdown
int age;
 │   │
 │   └── Variable Name
 │
 └────── Data Type
More Declarations
double salary;

boolean active;

char grade;

String name;

A declaration tells Java that a variable exists and what type of data it can hold.

Variable Initialization

Initialization means giving a variable its first value.

Initialization
int age;

age = 21;
Process
DECLARATION

int age;

        │
        ▼

INITIALIZATION

age = 21;

The variable is declared first and initialized later.

Variable Assignment

Assignment stores a value in a variable using the assignment operator.

Assignment
age = 21;
Assignment Direction
age = 21;
     │
     │
     ▼

VALUE ON THE RIGHT

        │
        ▼

STORED IN VARIABLE ON THE LEFT
Assignment is Not Equality
  • The = symbol assigns a value.
  • It does not mean mathematical equality.
  • The right-side expression is evaluated first.
  • The result is then assigned to the variable on the left.

Declaration and Initialization Together

A variable can be declared and initialized in a single statement.

Single Statement
int age = 21;
Complete Process
DECLARE VARIABLE

        +

PROVIDE FIRST VALUE

        │
        ▼

int age = 21;
Examples
String name = "Alex";

double price = 499.99;

boolean loggedIn = false;

char grade = 'A';

Reassigning Variable Values

A variable can usually receive a new value after its initial value has been assigned.

Reassignment
int score = 10;

System.out.println(score);

score = 20;

System.out.println(score);
Output
10
20
Value Change
INITIAL VALUE

score = 10

        │
        ▼

REASSIGNMENT

score = 20

        │
        ▼

CURRENT VALUE

20
Old Value
  • The variable now stores the new value.
  • The previous value is no longer the current value of that variable.
  • Later code reads the latest assigned value.

Declaring Multiple Variables

Multiple variables of the same type can be declared in one statement.

Multiple Declaration
int x, y, z;
Multiple Declaration and Initialization
int x = 10, y = 20, z = 30;

Although Java allows multiple variables in one declaration, separate declarations are often easier to read.

Recommended for Readability
int x = 10;

int y = 20;

int z = 30;

Copying Values Between Variables

Copying a Value
int first = 10;

int second = first;

System.out.println(second);
Output
10
Copy Process
first

┌──────────────┐
│      10      │
└──────────────┘

        │
        │ COPY VALUE
        ▼

second

┌──────────────┐
│      10      │
└──────────────┘
Independent Primitive Values
int first = 10;

int second = first;

second = 50;

System.out.println(first);
System.out.println(second);
Output
10
50

Variables in Expressions

Variables can be used in expressions to calculate new values.

Arithmetic Expression
int price = 100;

int quantity = 3;

int total = price * quantity;

System.out.println(total);
Output
300
Evaluation
price * quantity

100 * 3

        │
        ▼

300

        │
        ▼

STORED IN total

Types of Variables in Java

Based on where variables are declared and what they belong to, Java variables are commonly grouped into local variables, instance variables, and static variables.

Variable Categories
JAVA VARIABLES

├── Local Variables
│
├── Instance Variables
│
└── Static Variables

Local Variables

Declared inside methods, constructors, or blocks.

Instance Variables

Declared in a class and associated with individual objects.

Static Variables

Declared with static and associated with the class.

Local Variables

A local variable is declared inside a method, constructor, or block.

Local Variable
public class Main {

    public static void main(String[] args) {

        int age = 21;

        System.out.println(age);

    }

}
Local Variable Position
CLASS

└── METHOD

    └── LOCAL VARIABLE

        int age = 21;
Local Variable Characteristics
  • Declared inside a method, constructor, or block.
  • Accessible only within its valid scope.
  • Created when execution reaches its declaration as part of the containing execution context.
  • Does not receive a default value from Java.
  • Must be definitely assigned before being read.

Instance Variables

An instance variable is a non-static field declared inside a class but outside methods, constructors, and blocks.

Instance Variables
public class Student {

    String name;

    int age;

}
Different Objects
public class Student {

    String name;

    public static void main(String[] args) {

        Student first = new Student();
        first.name = "Alex";

        Student second = new Student();
        second.name = "Priya";

        System.out.println(first.name);
        System.out.println(second.name);
    }

}
Output
Alex
Priya
Separate Object State
OBJECT 1

name = "Alex"


OBJECT 2

name = "Priya"
Instance Variable Characteristics
  • Declared as a non-static class member.
  • Each object has its own instance state.
  • Exists as part of an object.
  • Receives a default value when the object is created.
  • Can be accessed through an appropriate object reference.

Static Variables

A static variable is a field declared with the static keyword. It belongs to the class rather than to each individual object.

Static Variable
public class Student {

    static String schoolName = "PrograMinds Academy";

}
Accessing a Static Variable
public class Student {

    static String schoolName = "PrograMinds Academy";

    public static void main(String[] args) {

        System.out.println(Student.schoolName);

    }

}
Class-Level Value
Student CLASS

        │
        ▼

schoolName

        │
        ▼

"PrograMinds Academy"
Static Variable Characteristics
  • Declared with the static keyword.
  • Belongs to the class.
  • One class-level variable is shared across uses of that class.
  • Receives a default value.
  • Commonly accessed using the class name.

Local vs Instance vs Static Variables

Comparison
LOCAL VARIABLE

Declared:
Inside method, constructor, or block

Belongs To:
Current execution context

Default Value:
No


INSTANCE VARIABLE

Declared:
Inside class without static

Belongs To:
Object

Default Value:
Yes


STATIC VARIABLE

Declared:
Inside class with static

Belongs To:
Class

Default Value:
Yes
All Three Types
public class Student {

    static String schoolName = "PrograMinds"; // Static

    String name;                              // Instance

    public void display() {

        int age = 21;                         // Local

        System.out.println(name);
        System.out.println(age);
        System.out.println(schoolName);
    }

}

Variable Scope

Scope defines the region of source code where a variable can be accessed by its name.

Scope Example
public static void main(String[] args) {

    int age = 21;

    System.out.println(age);

}
Scope Concept
{

    int age = 21;

    ┌─────────────────────┐
    │                     │
    │  age is accessible  │
    │                     │
    └─────────────────────┘

}
Outside the Scope
  • A variable name cannot be used everywhere in the program.
  • Its declaration location determines where it is accessible.
  • Trying to access a local variable outside its scope causes a compilation error.

Block Scope

A variable declared inside a block is accessible only within its valid scope inside that block.

Block Scope
public static void main(String[] args) {

    if (true) {

        int score = 100;

        System.out.println(score);

    }

}
Outside the Block
public static void main(String[] args) {

    if (true) {

        int score = 100;

    }

    System.out.println(score); // Error

}
Scope Boundary
if (true) {

    int score = 100;

    SCORE ACCESSIBLE

}

SCORE NOT ACCESSIBLE

Method Scope

A local variable declared in one method cannot be directly accessed by another method.

Separate Method Scope
public class Main {

    static void firstMethod() {

        int number = 10;

        System.out.println(number);
    }

    static void secondMethod() {

        // number is not accessible here

    }

}
Method Boundaries
firstMethod()

┌──────────────────┐
│ number = 10      │
│                  │
│ Accessible Here  │
└──────────────────┘


secondMethod()

┌──────────────────┐
│                  │
│ number unavailable│
└──────────────────┘

Parameter Scope

Method parameters are variables whose scope is associated with the method body.

Method Parameter
static void greet(String name) {

    System.out.println("Hello, " + name);

}
Parameter
greet(String name)
             │
             └── Parameter Variable

The parameter name can be used inside the method body but not as that same parameter outside the method.

Class-Level Scope

Fields are declared at class level and can be accessed by class members according to static context and access rules.

Class-Level Field
public class Student {

    String name;

    void setName() {

        name = "Alex";

    }

    void displayName() {

        System.out.println(name);

    }

}
Field Visibility Within Class
CLASS

├── FIELD: name
│
├── setName()
│   └── Can access name
│
└── displayName()
    └── Can access name

Nested Scope

Inner blocks can generally access variables declared in enclosing scopes when those variables are in scope.

Nested Scope
public static void main(String[] args) {

    int outer = 10;

    if (true) {

        int inner = 20;

        System.out.println(outer);
        System.out.println(inner);

    }

}
Nested Access
OUTER BLOCK

outer = 10

    │
    └── INNER BLOCK

        Can access outer

        inner = 20

Variable Lifetime

Variable lifetime refers to the period during program execution in which the variable or its associated storage exists.

Lifetime Concept
VARIABLE CREATED

        │
        ▼

VARIABLE EXISTS

        │
        ▼

VARIABLE USED

        │
        ▼

VARIABLE LIFETIME ENDS
Scope vs Lifetime
  • Scope is primarily about where a name can be accessed in source code.
  • Lifetime is about how long the associated variable or storage exists during execution.
  • Scope and lifetime are related but are not the same concept.

Local Variable Lifetime

Local Variable
static void calculate() {

    int result = 100;

    System.out.println(result);

}
Simplified Lifetime
METHOD CALLED

        │
        ▼

LOCAL VARIABLE DECLARED

        │
        ▼

LOCAL VARIABLE USED

        │
        ▼

METHOD COMPLETES

        │
        ▼

LOCAL VARIABLE LIFETIME ENDS

Instance Variable Lifetime

Instance variables exist as part of an object. Their lifetime is connected to the lifetime of that object.

Instance Lifetime
OBJECT CREATED

        │
        ▼

INSTANCE VARIABLES EXIST

        │
        ▼

OBJECT USED

        │
        ▼

OBJECT BECOMES UNREACHABLE

        │
        ▼

EVENTUALLY ELIGIBLE FOR
GARBAGE COLLECTION

Static Variable Lifetime

Static variables are associated with class-level state. They exist as part of the loaded class state for the relevant class-loading lifecycle.

Simplified Static Lifetime
CLASS INITIALIZED

        │
        ▼

STATIC VARIABLE AVAILABLE

        │
        ▼

USED THROUGH CLASS LIFECYCLE

Default Values

Instance and static variables receive default values when their containing object or class state is initialized.

Common Default Values
byte      → 0

short     → 0

int       → 0

long      → 0L

float     → 0.0f

double    → 0.0d

char      → '\u0000'

boolean   → false

Reference → null
Default Values Example
public class Main {

    int number;

    boolean active;

    String name;

    public static void main(String[] args) {

        Main object = new Main();

        System.out.println(object.number);
        System.out.println(object.active);
        System.out.println(object.name);

    }

}
Output
0
false
null

Local Variables Do Not Receive Default Values

Uninitialized Local Variable
public static void main(String[] args) {

    int age;

    System.out.println(age); // Compilation error

}

Java requires a local variable to be definitely assigned before its value is read.

Correct
public static void main(String[] args) {

    int age = 21;

    System.out.println(age);

}
Remember
  • Fields receive default values.
  • Local variables do not automatically receive usable default values.
  • Initialize local variables before reading them.

Primitive Variables

A primitive variable stores a primitive value of one of Java's eight primitive types.

Primitive Variables
byte level = 5;

short year = 2026;

int age = 21;

long population = 8000000000L;

float temperature = 36.5f;

double salary = 50000.75;

char grade = 'A';

boolean active = true;
Primitive Concept
int age = 21;

age

┌──────────────┐
│      21      │
└──────────────┘

PRIMITIVE VALUE

Reference Variables

A reference variable holds a reference that can refer to an object rather than directly containing the complete object itself.

Reference Variable
String name = "Alex";
Object Reference
Student student = new Student();
Simplified Reference Concept
student

┌──────────────┐
│  REFERENCE   │
└──────────────┘
        │
        │
        ▼
┌──────────────────────┐
│                      │
│    Student Object    │
│                      │
└──────────────────────┘
Simplified Model
  • A reference variable is not the object itself.
  • It stores a reference used to access an object.
  • Reference behavior will become clearer in the Classes and Objects lessons.

Primitive vs Reference Variables

Comparison
PRIMITIVE VARIABLE

int age = 21;

Variable stores:
Primitive value


REFERENCE VARIABLE

Student student = new Student();

Variable stores:
Reference to an object
Example
int age = 21;

String name = "Alex";

Student student = new Student();
Later Lessons
  • Primitive types are covered in Lesson 9.
  • Objects are covered in Lesson 18.
  • The difference between value copying and reference copying will become more important later.

The var Keyword

Java supports local variable type inference using var. The compiler determines the variable type from the initializer.

Using var
var age = 21;

var name = "Alex";

var price = 99.99;

var active = true;
Type Inference
var age = 21;

        │
        ▼

COMPILER EXAMINES INITIALIZER

        │
        ▼

21 IS int

        │
        ▼

age HAS TYPE int
var is Still Statically Typed
  • var does not make Java dynamically typed.
  • The compiler determines a specific type.
  • The variable keeps that inferred type.
Type Does Not Change
var age = 21;

// age is inferred as int

age = 30;

// age = "Thirty"; // Error

Requirements for var

A local variable declared with var must have enough information in its initializer for the compiler to infer a type.

Valid var Declarations
var number = 10;

var message = "Hello";

var price = 25.50;
Invalid Without Initializer
var number; // Error
Key Requirement
  • var requires an initializer.
  • The initializer must allow a type to be inferred.
  • var is used for local variable type inference.

Limitations of var

Valid Local Variable
public static void main(String[] args) {

    var age = 21;

}
Invalid Field
public class Student {

    // var name = "Alex"; // Error

}
Invalid Parameter
// void greet(var name) { }
Invalid Return Type
// var getName() {
//     return "Alex";
// }
var Cannot Replace Every Type
  • It cannot be used as a field type.
  • It cannot be used as a normal method parameter type.
  • It cannot be used as a method return type.
  • It is primarily for local variable declarations with initializers.

Explicit Type vs var

Explicit Type
String message = "Hello";
Type Inference
var message = "Hello";

Both variables have the type String. The difference is whether the type is written explicitly or inferred by the compiler.

Choose for Readability
  • Use an explicit type when it makes the code clearer.
  • Use var when the type is obvious and it improves readability.
  • Do not use var merely to hide important type information.

Variable Naming Rules

Java identifiers must follow language rules.

  • A variable name cannot begin with a digit.
  • A variable name can contain letters.
  • A variable name can contain digits after a valid beginning.
  • The underscore character can appear in an identifier.
  • The dollar sign can appear in an identifier.
  • A reserved keyword cannot be used as a variable name.
  • Variable names are case-sensitive.
  • Whitespace cannot appear inside a variable name.
Valid Names
int age;

int studentAge;

int age2;

int _count;

int totalAmount;

Variable Naming Conventions

Java variables conventionally use camelCase.

camelCase
studentName

accountBalance

totalPrice

isLoggedIn

maximumScore
camelCase Pattern
studentName
       │
       └── Second word begins with uppercase letter


totalAccountBalance
     │      │
     │      └── Third word begins uppercase
     │
     └───────── Second word begins uppercase
Recommended Style
  • Begin variable names with a lowercase letter.
  • Use camelCase for multiple words.
  • Choose names that explain the stored value.
  • Avoid unnecessary abbreviations.

Valid Variable Names

Valid Examples
int age;

int studentAge;

int score1;

int _counter;

int totalPrice;

boolean isActive;

String firstName;
Recommended Names
age

studentAge

accountBalance

productPrice

employeeName

isAvailable

totalScore

Invalid Variable Names

Invalid Examples
// int 2age;

// int student age;

// int class;

// int total-price;

// int first.name;
Why Invalid?
2age

Starts with a digit


student age

Contains whitespace


class

Reserved keyword


total-price

Contains invalid hyphen


first.name

Contains a dot

Variable Names are Case-Sensitive

Different Variables
int age = 21;

int Age = 30;

int AGE = 40;

System.out.println(age);
System.out.println(Age);
System.out.println(AGE);
Output
21
30
40
Avoid Confusing Names
  • age, Age, and AGE are different identifiers.
  • Using names that differ only by capitalization can confuse readers.
  • Follow consistent naming conventions.

Reserved Words Cannot Be Variable Names

Invalid
// int class = 10;

// int public = 20;

// int static = 30;

// int if = 40;

Keywords have special meanings in the Java language and cannot be used as ordinary variable names.

Examples of Keywords
class

public

private

static

void

int

if

else

for

while

return

new

Use Meaningful Variable Names

Poor Names
int a = 21;

double x = 499.99;

String s = "Alex";
Better Names
int studentAge = 21;

double productPrice = 499.99;

String studentName = "Alex";
Good Names Explain Intent
  • Use age instead of a.
  • Use totalPrice instead of tp when clarity matters.
  • Use accountBalance instead of value.
  • Use isLoggedIn for a boolean representing login state.

Variable Shadowing

Variable shadowing occurs when a variable in a narrower scope uses the same name as a variable in an enclosing context, causing the nearer declaration to be selected by the simple name.

Field Shadowed by Parameter
public class Student {

    String name;

    void setName(String name) {

        name = name;

    }

}
Problem
FIELD

name

        │
        │ SHADOWED BY
        ▼

PARAMETER

name

Inside the method, the simple name name refers to the parameter. To access the current object's field, use this.name.

Using this with Variables

Using this
public class Student {

    String name;

    void setName(String name) {

        this.name = name;

    }

}
Meaning
this.name = name;
     │        │
     │        └── Parameter
     │
     └─────────── Current Object's Field
Later OOP Topic
  • The this keyword will be studied in greater detail with classes, objects, and constructors.
  • For now, understand that this.name can distinguish an instance field from a parameter with the same name.

Method Parameters are Variables

Method Parameters
static int add(int first, int second) {

    return first + second;

}
Parameters
add(int first, int second)
        │          │
        │          └── Parameter Variable
        │
        └───────────── Parameter Variable
Passing Arguments
int result = add(10, 20);

System.out.println(result);
Simplified Flow
ARGUMENTS

10, 20

        │
        ▼

PARAMETERS

first = 10
second = 20

        │
        ▼

RETURN

30

Variables and Memory

Variables are connected to memory used by the running program. The exact memory behavior depends on the variable type, declaration context, object layout, JVM implementation, and runtime optimizations.

Simplified View
VARIABLE

age

        │
        ▼

VALUE

21

        │
        ▼

USED BY RUNNING PROGRAM
Do Not Oversimplify Memory
  • The JVM can optimize program execution.
  • A source-level variable does not always map to one permanent physical memory box.
  • Use stack and heap diagrams as learning models, not as complete JVM specifications.

Stack and Heap Overview

A common beginner model associates method execution and many local values with stack frames, while objects are generally allocated in heap memory.

Example
public static void main(String[] args) {

    int age = 21;

    Student student = new Student();

}
Simplified Memory Model
METHOD EXECUTION AREA

age = 21

student = reference
            │
            │
            ▼

        HEAP

┌──────────────────┐
│  Student Object  │
└──────────────────┘
Simplified Learning Model
  • Local primitive values are commonly explained through method stack frames.
  • Reference variables can hold references to objects.
  • Objects are generally allocated in heap memory.
  • Actual JVM implementation details and optimizations can be more complex.

How Variable Values Change

Changing a Value
int balance = 1000;

balance = 1500;

balance = balance - 200;

System.out.println(balance);
Value Flow
balance = 1000

        │
        ▼

balance = 1500

        │
        ▼

balance = 1500 - 200

        │
        ▼

balance = 1300
Output
1300

Swapping Variable Values

A temporary variable can be used to exchange the values of two variables.

Swap Values
int first = 10;

int second = 20;

int temporary = first;

first = second;

second = temporary;

System.out.println(first);
System.out.println(second);
Output
20
10
Swap Process
START

first = 10
second = 20


STEP 1

temporary = 10


STEP 2

first = 20


STEP 3

second = 10


RESULT

first = 20
second = 10

Temporary Variables

A temporary variable stores an intermediate value needed for a short part of a calculation or process.

Temporary Result
int price = 100;

int quantity = 5;

int subtotal = price * quantity;

int tax = 50;

int total = subtotal + tax;

System.out.println(total);
Calculation Flow
price × quantity

        │
        ▼

subtotal

        │
        ▼

subtotal + tax

        │
        ▼

total

Uninitialized Variables

Invalid Local Variable Use
public static void main(String[] args) {

    int number;

    System.out.println(number);

}

The local variable number has been declared but has not been definitely assigned before it is read.

Correct
public static void main(String[] args) {

    int number = 10;

    System.out.println(number);

}

Unused Variables

Unused Variable
public static void main(String[] args) {

    int age = 21;

    System.out.println("Hello");

}

The variable age is declared but never used. Unused variables make code harder to understand and can indicate unfinished or unnecessary logic.

Remove Unnecessary Variables
  • Delete variables that serve no purpose.
  • Do not create variables merely to make the program look complex.
  • Keep only data that the logic actually needs.

Common Variable Errors

Common Errors
VARIABLE ERRORS

├── Using Variable Before Declaration
├── Reading Uninitialized Local Variable
├── Assigning Incompatible Type
├── Accessing Variable Outside Scope
├── Using Reserved Keyword as Name
├── Starting Name with Digit
├── Forgetting Case Sensitivity
├── Accidental Variable Shadowing
├── Using var Without Initializer
├── Using var as Field Type
├── Confusing Field and Local Variable
└── Declaring Unused Variables
Use Before Declaration
// System.out.println(age);

int age = 21;
Incompatible Type
int age = 21;

// age = "Twenty One";
Outside Scope
if (true) {

    int score = 100;

}

// System.out.println(score);
Case Error
int age = 21;

// System.out.println(Age);
Check These First
  • Was the variable declared?
  • Was it initialized before being read?
  • Is the assigned value compatible with the variable type?
  • Is the variable currently in scope?
  • Is the capitalization correct?
  • Is the name a valid Java identifier?
  • Is a local variable unintentionally hiding a field?

Best Practices

  • Use meaningful variable names.
  • Use camelCase for normal variable names.
  • Begin variable names with lowercase letters by convention.
  • Avoid names that differ only by capitalization.
  • Keep variable scope as narrow as practical.
  • Declare variables close to where they are first used.
  • Initialize local variables before reading them.
  • Avoid unnecessary variables.
  • Remove unused variables.
  • Use the correct data type for the value.
  • Do not use one variable for unrelated purposes.
  • Avoid unclear one-letter names except in small conventional contexts.
  • Use boolean names that communicate a condition clearly.
  • Use names such as isActive, hasAccess, and canEdit for boolean values when appropriate.
  • Use plural names for collections of multiple items.
  • Use singular names for individual values.
  • Avoid unnecessary abbreviations.
  • Avoid excessive variable shadowing.
  • Use this when it improves clarity between fields and parameters.
  • Access static variables through the class name when appropriate.
  • Understand whether data belongs to a method, object, or class before choosing the variable category.
  • Use explicit types when they improve readability.
  • Use var only for local variables where type inference is clear.
  • Do not assume local variables receive default values.
  • Remember that fields receive default values.
  • Keep temporary variables focused on one purpose.
  • Do not confuse variable scope with variable lifetime.
  • Use comments only when the variable purpose is not already clear from the code.
  • Prefer readable code over unnecessarily short code.
  • Follow the naming and formatting conventions of the project.

Variable Checklist

Checklist
VARIABLE CHECKLIST

[ ] Variable has a valid data type

[ ] Variable has a valid name

[ ] Name does not begin with a digit

[ ] Name contains no whitespace

[ ] Name is not a reserved keyword

[ ] Name follows camelCase convention

[ ] Name clearly describes the stored value

[ ] Variable is declared before use

[ ] Local variable is initialized before reading

[ ] Assigned value matches the variable type

[ ] Variable is accessed within its scope

[ ] Variable has the correct category

[ ] Local data is stored locally

[ ] Object-specific data uses instance fields

[ ] Shared class data uses static fields when appropriate

[ ] var is used only in a valid local context

[ ] var declaration includes an initializer

[ ] Shadowing is intentional and understandable

[ ] this is used when needed for field clarity

[ ] Variable is actually used

[ ] Variable scope is not unnecessarily broad

Common Misconceptions

Avoid These Misconceptions
  • A variable is not simply a permanent physical box in memory.
  • A variable has a type in Java.
  • The = operator performs assignment.
  • The = operator does not mean mathematical equality.
  • The right side of an assignment is evaluated before the result is stored on the left.
  • Declaration and initialization are different operations.
  • A variable can be declared without being initialized.
  • A local variable cannot be read before definite assignment.
  • Local variables do not automatically receive default values.
  • Instance variables receive default values.
  • Static variables receive default values.
  • A variable can usually be reassigned unless additional language rules prevent it.
  • Reassignment replaces the current value associated with that variable.
  • Variable names are case-sensitive.
  • age and Age are different identifiers.
  • A reserved keyword cannot be used as a variable name.
  • A variable name cannot begin with a digit.
  • A variable name cannot contain spaces.
  • Scope and lifetime are not the same thing.
  • A variable declared inside a block is not accessible everywhere in the method.
  • A local variable in one method is not directly available in another method.
  • Method parameters are variables.
  • Instance variables belong to objects.
  • Static variables belong to classes.
  • Different objects can have different instance field values.
  • A static variable is shared at class level.
  • A primitive variable stores a primitive value.
  • A reference variable is not the object itself.
  • A reference variable can refer to an object.
  • Copying a primitive variable copies its primitive value.
  • Reference copying behaves differently from copying primitive values.
  • var does not make Java dynamically typed.
  • var does not mean the variable can later change to another unrelated type.
  • var requires an initializer.
  • var cannot be used as a normal field type.
  • var cannot replace every explicit type in Java.
  • Using var is not always more readable.
  • The shortest variable name is not always the best variable name.
  • One-letter variable names are not suitable for most business data.
  • Variable shadowing can make code confusing.
  • this.name and name can refer to different variables.
  • A field and a local variable are not the same.
  • Unused variables do not improve a program.
  • Wider scope is not always better.
  • Variables should generally be declared close to where they are needed.
  • Stack and heap diagrams are simplified learning models.
  • Actual JVM execution and optimization can be more complex than beginner memory diagrams.

Practice Exercises

Exercise 1: Basic Variables
  • Create a variable for your name.
  • Create a variable for your age.
  • Create a variable for your height.
  • Create a variable for whether you are learning Java.
  • Print all values.
Exercise 2: Declaration and Initialization
  • Declare an int variable without initialization.
  • Initialize it on the next line.
  • Print the value.
  • Reassign a new value.
  • Print the new value.
Exercise 3: Product Calculation
  • Create a variable named productPrice.
  • Create a variable named quantity.
  • Calculate the total price.
  • Store the result in another variable.
  • Print the result.
Exercise 4: Swap Values
  • Create first with value 10.
  • Create second with value 20.
  • Use a temporary variable.
  • Swap the values.
  • Print both variables before and after swapping.
Exercise 5: Variable Scope
  • Create a variable inside main.
  • Create an if block.
  • Access the outer variable inside the block.
  • Create another variable inside the block.
  • Try to access the inner variable outside the block.
  • Observe and explain the compilation error.
Exercise 6: Variable Categories
  • Create one static variable.
  • Create one instance variable.
  • Create one local variable.
  • Print all three from valid contexts.
  • Identify what each variable belongs to.
Exercise 7: Default Values
  • Create an int instance field.
  • Create a boolean instance field.
  • Create a String instance field.
  • Create an object.
  • Print all fields without explicitly initializing them.
  • Write down the default values.
Exercise 8: Local Variable Initialization
  • Declare a local int variable.
  • Try to print it before initialization.
  • Observe the compilation error.
  • Initialize the variable.
  • Run the program again.
Exercise 9: Use var
  • Create an int value using var.
  • Create a String value using var.
  • Create a double value using var.
  • Try to declare var without an initializer.
  • Explain why the invalid declaration fails.
Exercise 10: Variable Shadowing
  • Create a class with a field named name.
  • Create a method with a parameter named name.
  • Assign the parameter to the field using this.name.
  • Print the field value.
  • Explain which name refers to the parameter and which refers to the field.

Common Interview Questions

What is a variable in Java?

A variable is a named storage location used to hold a value that a program can access.

What is variable declaration?

Declaration introduces a variable by specifying its type and name.

What is variable initialization?

Initialization gives a variable its first value.

What is assignment?

Assignment stores a value in a variable using the assignment operator.

What are the main categories of variables in Java?

They are commonly categorized as local variables, instance variables, and static variables.

What is a local variable?

A local variable is declared inside a method, constructor, or block.

What is an instance variable?

An instance variable is a non-static field associated with an object.

What is a static variable?

A static variable is a field declared with static and associated with the class.

Do local variables receive default values?

No. Local variables must be definitely assigned before their values are read.

Do instance variables receive default values?

Yes. Instance variables receive default values when an object is created.

Do static variables receive default values?

Yes. Static variables receive default values as part of class initialization.

What is variable scope?

Scope is the region of source code where a variable can be accessed by its name.

What is variable lifetime?

Lifetime is the period during execution in which the variable or associated storage exists.

What is the difference between scope and lifetime?

Scope concerns where a name can be accessed in source code, while lifetime concerns how long the variable or associated storage exists during execution.

What is variable shadowing?

Shadowing occurs when a declaration in a narrower scope uses the same name as a variable in an enclosing context.

Why is this used with fields?

this can explicitly refer to the current object and distinguish an instance field from a parameter or local variable with the same name.

What is a primitive variable?

A primitive variable stores a primitive value.

What is a reference variable?

A reference variable holds a reference that can refer to an object.

What does var do in Java?

var enables local variable type inference, allowing the compiler to determine the variable type from its initializer.

Does var make Java dynamically typed?

No. The compiler infers a specific static type for the variable.

Can var be used for fields?

No. var cannot be used as a normal field type.

Can a variable name begin with a number?

No. A Java identifier cannot begin with a digit.

Are Java variable names case-sensitive?

Yes. age, Age, and AGE are different identifiers.

Can a Java keyword be used as a variable name?

No. Reserved keywords cannot be used as ordinary variable names.

Frequently Asked Questions

Can I declare a variable without assigning a value?

Yes. However, a local variable must be definitely assigned before its value is read.

Can I change the value of a variable?

Yes. A normal variable can generally be reassigned with another compatible value unless additional language rules prevent reassignment.

Can I change the type of a variable?

No. A variable has a fixed type. You cannot change an int variable into a String variable.

Can two variables have the same name?

They can exist in different valid scopes, but Java rules prevent conflicting declarations in scopes where the names would be ambiguous or illegally redeclared.

Can a local variable have the same name as a field?

Yes. The local variable or parameter can shadow the field. this can be used to refer explicitly to the current object's field.

What happens to the old value after reassignment?

The variable now represents the newly assigned value. The old value is no longer the current value of that variable.

Should I initialize every variable immediately?

Initialize variables when you have a meaningful value. Local variables must be definitely assigned before reading them.

Why do fields get default values but local variables do not?

Java initializes object and class state with defined defaults, while local variable definite-assignment rules require the programmer or control flow to establish a value before reading it.

Can I declare multiple variables on one line?

Yes, when they share the same declared type, but separate declarations are often more readable.

Should I always use var?

No. Use var when the inferred type is clear and readability improves. Explicit types are often better when they communicate useful information.

Can var be initialized with null?

A declaration such as var value = null cannot provide a standalone type for inference.

Can I use var for method parameters?

Not as a normal replacement for an explicit method parameter type.

Can I use var as a return type?

No. Method return types must be declared explicitly.

What is the best variable name?

A good variable name clearly communicates what the value represents in its context.

Are one-letter variable names always bad?

No. They can be reasonable in small conventional contexts such as simple loop counters, but descriptive names are better for most application data.

What is the difference between a field and a variable?

A field is a specific kind of variable declared as a member of a class. Local variables and parameters are other variable categories.

Can a static method directly access an instance variable?

A static method does not have an implicit current object, so it needs an appropriate object reference to access an instance variable.

Can an instance method access a static variable?

Yes. An instance method can access static members, though static variables are commonly qualified with the class name for clarity.

Where are variables stored in memory?

The exact answer depends on variable kind, runtime behavior, JVM implementation, and optimization. Beginner stack-and-heap diagrams are useful simplified models.

What should I learn after variables?

The next lesson covers constants, which are used for values that should not be reassigned after initialization.

Key Takeaways

  • Variables store values used by programs.
  • A variable has a type.
  • A variable has a name.
  • A variable can hold a compatible value.
  • Declaration introduces a variable.
  • Initialization gives a variable its first value.
  • Assignment stores a value in a variable.
  • The assignment operator is =.
  • The right side of an assignment is evaluated first.
  • The result is stored in the variable on the left.
  • Declaration and initialization can occur separately.
  • Declaration and initialization can occur in one statement.
  • Variables can usually be reassigned.
  • Reassignment changes the current value.
  • Multiple variables of the same type can be declared together.
  • Separate declarations are often more readable.
  • Values can be copied between compatible variables.
  • Primitive value copying creates independent primitive values.
  • Variables can participate in expressions.
  • Java variables are commonly categorized as local, instance, and static variables.
  • Local variables are declared inside methods, constructors, or blocks.
  • Instance variables are non-static fields.
  • Instance variables belong to objects.
  • Different objects can have different instance values.
  • Static variables are declared with static.
  • Static variables belong to the class.
  • Static variables represent class-level state.
  • Scope determines where a variable name is accessible.
  • Block variables have limited scope.
  • Local variables in one method are not directly accessible in another method.
  • Method parameters are variables.
  • Fields have class-level declaration scope subject to Java access rules.
  • Inner blocks can access valid variables from enclosing scopes.
  • Lifetime describes how long a variable or associated storage exists during execution.
  • Scope and lifetime are different concepts.
  • Local variable lifetime is connected to the containing execution context.
  • Instance variables exist as part of objects.
  • Static variables exist as part of class-level state.
  • Instance fields receive default values.
  • Static fields receive default values.
  • Local variables do not automatically receive usable default values.
  • Local variables must be definitely assigned before reading.
  • Primitive variables store primitive values.
  • Reference variables hold references that can refer to objects.
  • A reference variable is not the object itself.
  • var provides local variable type inference.
  • var requires an initializer.
  • var still produces a statically typed variable.
  • var cannot be used as a normal field type.
  • var cannot be used as a normal method return type.
  • var cannot replace every explicit type.
  • Variable names must follow Java identifier rules.
  • Variable names cannot begin with digits.
  • Variable names cannot contain whitespace.
  • Reserved keywords cannot be variable names.
  • Java identifiers are case-sensitive.
  • Normal variable names conventionally use camelCase.
  • Meaningful names improve readability.
  • Boolean names should clearly represent conditions.
  • Variable shadowing occurs when a nearer declaration hides another variable with the same name.
  • this can distinguish an instance field from a parameter or local variable.
  • Method parameters receive values from method arguments.
  • Memory diagrams are simplified learning models.
  • Objects are generally explained as heap-allocated.
  • Method execution is commonly explained using stack frames.
  • Temporary variables can hold intermediate values.
  • Temporary variables are useful for swapping values.
  • Uninitialized local variables cannot be read.
  • Unused variables should normally be removed.
  • Variables should have the narrowest practical scope.
  • Variables should be declared close to where they are used.
  • One variable should not be reused for unrelated purposes.
  • Choosing the correct variable category improves program design.
  • Understanding variables is essential before learning constants and data types.

Summary

A variable is a named storage location used to hold a value that a Java program can access. Every variable has a type and a name, and it can hold values compatible with its type.

Variable declaration introduces a variable, initialization gives it its first value, and assignment stores a value in it. Variables can usually be reassigned, allowing programs to represent changing data.

Java variables are commonly divided into local variables, instance variables, and static variables. Local variables exist inside methods, constructors, or blocks. Instance variables belong to objects, while static variables belong to classes.

Scope determines where a variable name can be accessed. Variables declared inside blocks have limited scope, method parameters are available within their method context, and fields can be accessed by class members according to Java access and static-context rules.

Lifetime describes how long a variable or its associated storage exists during execution. Local, instance, and static variables have different lifetime characteristics.

Instance and static fields receive default values. Local variables do not automatically receive usable default values and must be definitely assigned before their values are read.

Primitive variables store primitive values, while reference variables hold references that can refer to objects. This difference becomes increasingly important when working with objects, arrays, methods, and collections.

Java supports local variable type inference using var. The compiler determines the variable type from its initializer, but the variable remains statically typed.

Good variable names follow Java naming rules and conventions. Normal variables conventionally use camelCase, names should be meaningful, and reserved keywords cannot be used as identifiers.

Variable shadowing occurs when a nearer declaration uses the same name as another variable. The this keyword can distinguish an instance field from a parameter or local variable with the same name.

Understanding declaration, initialization, assignment, scope, lifetime, variable categories, default values, type inference, and naming rules provides the foundation for nearly every Java topic that follows.

Lesson 7 Completed
  • You understand what a variable is.
  • You understand why programs need variables.
  • You understand the variable container analogy.
  • You understand variable structure.
  • You can declare variables.
  • You can initialize variables.
  • You can assign values.
  • You understand the assignment operator.
  • You can declare and initialize a variable together.
  • You can reassign variable values.
  • You understand what happens to the current value after reassignment.
  • You can declare multiple variables.
  • You understand why separate declarations can improve readability.
  • You can copy values between variables.
  • You understand primitive value copying.
  • You can use variables in expressions.
  • You know the three main variable categories.
  • You understand local variables.
  • You understand instance variables.
  • You understand static variables.
  • You can compare local, instance, and static variables.
  • You understand variable scope.
  • You understand block scope.
  • You understand method scope.
  • You understand parameter scope.
  • You understand class-level field access.
  • You understand nested scope.
  • You understand variable lifetime.
  • You understand local variable lifetime.
  • You understand instance variable lifetime.
  • You understand static variable lifetime.
  • You understand the difference between scope and lifetime.
  • You know which variables receive default values.
  • You know that local variables do not receive automatic usable defaults.
  • You understand definite assignment for local variables.
  • You understand primitive variables.
  • You understand reference variables.
  • You understand the basic difference between primitive and reference variables.
  • You understand local variable type inference.
  • You can use var correctly.
  • You understand the requirements of var.
  • You understand the limitations of var.
  • You understand that var does not make Java dynamically typed.
  • You can choose between explicit types and var.
  • You understand Java variable naming rules.
  • You understand Java variable naming conventions.
  • You can identify valid variable names.
  • You can identify invalid variable names.
  • You understand Java case sensitivity.
  • You know that reserved words cannot be variable names.
  • You understand the importance of meaningful names.
  • You understand variable shadowing.
  • You understand the basic purpose of this with fields.
  • You understand that method parameters are variables.
  • You understand a simplified view of variables and memory.
  • You understand the basic stack and heap learning model.
  • You can track variable value changes.
  • You can swap two variable values.
  • You understand temporary variables.
  • You can identify uninitialized local variable errors.
  • You understand why unused variables should be removed.
  • You can identify common variable mistakes.
  • You know the best practices for working with Java variables.
  • You are ready to learn constants in Java.
Next Lesson →

Constants in Java