Java Variables
A variable is a named container that stores a value.
Every piece of data your program works with — a user's age, a bank balance, a name, a temperature reading — lives in a variable. Variables are the most fundamental building block of any program.
👉 What you'll learn here:
- ›How to declare and initialize variables in Java
- ›The three types of variables and where each is used
- ›Variable scope — where a variable lives and dies
- ›
finalvariables — values that never change
🧘 Variables are simple — but the details matter.
Java follows stricter variable rules than Python and JavaScript. Even if you've used variables before, the sections on scope and variable types are worth reading carefully.
Declaring a Variable
In Java, you must declare a variable before you use it. A declaration tells Java two things: the type of data it will hold and the name you're giving it.
int age; // declared, not yet initialized
String name; // declared, not yet initialized
double salary; // declared, not yet initializedA variable that has been declared but not given a value is uninitialized. You cannot use it yet.
Initializing a Variable
Initialization means assigning a value to a variable for the first time.
int age = 25; // declared and initialized in one line
String name = "Arjun"; // declared and initialized in one line
double salary = 75000.50; // declared and initialized in one lineYou can also declare first and initialize later:
int age; // declare
age = 25; // initialize later⚠️ Local variables must be initialized before use. If you try to use a local variable before giving it a value, the compiler throws an error:
int score;
System.out.println(score); // ❌ error: variable score might not have been initialized
int score = 0;
System.out.println(score); // ✅ works fineVariable Syntax — The Pattern
Every variable declaration follows the same pattern:
dataType variableName = value;
int age = 25;
// ↑ ↑ ↑
// type name value- ›
int— the data type. Tells Java what kind of value this holds. - ›
age— the name. You choose this. Follow camelCase convention. - ›
= 25— the initial value. Optional at declaration, required before first use. - ›
;— the semicolon. Ends the statement.
Updating a Variable
Once declared, you can change a variable's value at any time — just assign a new value without repeating the type.
int score = 0;
System.out.println(score); // 0
score = 50; // update — no 'int' keyword
System.out.println(score); // 50
score = score + 10; // update using its own value
System.out.println(score); // 60⚠️ Common mistake: Writing the type again when updating:
int score = 0;
int score = 50; // ❌ error: variable 'score' is already definedThe type is written once — at declaration. Updates never repeat it.
The Three Types of Variables in Java
Java has three categories of variables. Where you declare a variable determines what type it is and how long it lives.
1. Local Variables
Declared inside a method. They exist only while that method is running.
public static void main(String[] args) {
int age = 25; // local variable
String name = "Arjun"; // local variable
System.out.println(name + " is " + age);
}
// 'age' and 'name' no longer exist after the method ends- ›Must be initialized before use — no default value
- ›Cannot be accessed from outside the method
2. Instance Variables
Declared inside a class but outside any method. Each object of the class gets its own copy.
💡 Classroom analogy: Think of a classroom. Each student has their own name — that's an instance variable. Every student's name is separate and belongs to them individually.
public class Student {
// Each Student object gets its OWN copy of these:
String name;
int age;
double gpa;
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Priya";
s1.gpa = 9.1;
Student s2 = new Student();
s2.name = "Arjun";
s2.gpa = 8.4;
System.out.println(s1.name + ": " + s1.gpa); // Priya: 9.1
System.out.println(s2.name + ": " + s2.gpa); // Arjun: 8.4
}
}- ›Each object has its own copy —
s1.nameands2.nameare completely separate - ›Get default values automatically (
0,false,null) if not initialized
3. Static Variables
Declared with the static keyword. Shared by all objects — there is only one copy, no matter how many objects exist.
💡 Classroom analogy continued: The total number of students in the classroom is shared by everyone — that's a static variable. There's only one count, and it belongs to the classroom itself, not to any individual student.
public class Student {
String name; // instance — each student has their own name
static int totalStudents = 0; // static — ONE shared count for all
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Priya";
totalStudents++;
Student s2 = new Student();
s2.name = "Arjun";
totalStudents++;
System.out.println("Total students: " + totalStudents); // 2
}
}- ›One copy shared across all objects — not per object
- ›Get default values like instance variables
- ›Exist for the entire lifetime of the program
Variable Scope
💡 Scope feels confusing at first for almost every beginner — and that's completely normal.
The easiest way to think about it: a variable only exists inside the block { } where it was created. The moment that block closes, the variable is gone.
public class ScopeDemo {
static int classLevel = 100; // accessible everywhere in this class
public static void main(String[] args) {
int methodLevel = 50; // accessible within main()
if (methodLevel > 10) {
int blockLevel = 20; // accessible ONLY inside this if-block
System.out.println(classLevel); // ✅ 100
System.out.println(methodLevel); // ✅ 50
System.out.println(blockLevel); // ✅ 20
}
System.out.println(classLevel); // ✅ 100
System.out.println(methodLevel); // ✅ 50
System.out.println(blockLevel); // ❌ error — blockLevel out of scope
}
}Loop variables are also scoped to the loop:
for (int i = 0; i < 5; i++) {
System.out.println(i); // ✅ i exists here
}
System.out.println(i); // ❌ error — i is gone after the loop endsfinal Variables — Constants
Adding final to a variable means its value cannot be changed after initialization.
final int MAX_SCORE = 100;
MAX_SCORE = 200; // ❌ error: cannot assign a value to final variable MAX_SCOREBy convention, final variables use UPPER_SNAKE_CASE:
final int MAX_SIZE = 50;
final double TAX_RATE = 0.18;
final String DEFAULT_COUNTRY = "India";At the class level, static final creates a true program-wide constant:
public class Config {
static final int MAX_USERS = 1000;
static final String VERSION = "2.0";
}A Complete Example
This program uses all three variable types together so you can see them side by side:
public class BankAccount {
String owner; // instance — each account has its own owner
double balance; // instance — each account has its own balance
static int totalAccounts = 0; // static — shared count across all accounts
static final double MIN_BALANCE = 500; // constant — never changes
public void deposit(double amount) {
double newBalance = balance + amount; // local — exists only in this method
balance = newBalance;
System.out.println("Deposited: ₹" + amount);
System.out.println("Balance: ₹" + balance);
}
public static void main(String[] args) {
BankAccount acc1 = new BankAccount();
acc1.owner = "Priya";
acc1.balance = 10000.0;
totalAccounts++;
BankAccount acc2 = new BankAccount();
acc2.owner = "Arjun";
acc2.balance = 25000.0;
totalAccounts++;
acc1.deposit(5000.0);
System.out.println("Owner: " + acc1.owner);
System.out.println("Minimum balance: ₹" + MIN_BALANCE);
System.out.println("Total accounts: " + totalAccounts);
}
}Output:
Deposited: ₹5000.0
Balance: ₹15000.0
Owner: Priya
Minimum balance: ₹500.0
Total accounts: 2
Type Inference with var — Optional (Java 10+)
📌 This is an optional topic. Master explicit type declarations first. Come back to var once you're comfortable with the basics.
From Java 10 onwards, you can use var instead of writing the type explicitly. Java infers the type from the assigned value.
var age = 25; // Java infers: int
var name = "Arjun"; // Java infers: String
var price = 99.99; // Java infers: double
var isActive = true; // Java infers: booleanvar only works for local variables initialized at the point of declaration:
var score; // ❌ error — can't infer type without a valueUse var when the type is obvious from the right side. Spell it out when it isn't — readability comes first.
Common Mistakes — Quick Reference
| Mistake | Broken Code | Fix |
|---|---|---|
| Using before declaring | println(age); int age = 5; | Declare before use |
| Using uninitialized local | int x; println(x); | Initialize: int x = 0; |
| Repeating type on update | int count = 0; int count = 1; | count = 1; — no type |
| Accessing out of scope | if (...) { int x = 1; } println(x); | Declare x before the if |
Reassigning final | final int MAX = 10; MAX = 20; | final values cannot change |
| Wrong type assignment | int age = "twenty"; | Match type: int age = 20; |
The 3 Things to Remember From This Page
- ›Declare with type, update without —
int age = 25;to create,age = 30;to update. Writing the type again on update is a compile error. - ›Local variables have no default — they must be initialized before use. Instance and static variables get automatic defaults (
0,false,null). - ›Scope controls visibility — a variable only exists inside the
{ }where it was created. Outside that block, it doesn't exist.
Summary
- ›A variable is a named container that stores a value
- ›Declare with:
dataType variableName = value; - ›Three types: local (inside method), instance (inside class), static (shared across all objects)
- ›Instance variables belong to each object individually — like each student's name
- ›Static variables belong to the class and are shared by all — like the total student count
- ›Local variables must be initialized before use — no automatic default
- ›
finalmakes a variable's value unchangeable — use UPPER_SNAKE_CASE - ›Scope — a variable is accessible only within the
{ }where it was declared - ›
var(Java 10+) — optional shorthand that lets Java infer the type automatically
What to Read Next
Learn how to convert one data type into another.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Adds two fixed integers and prints the result.
Swaps the values of two integers using a temporary third variable.
Swaps the values of two integers without using any extra storage.
Computes simple interest from a principal amount, annual rate, and time in years.