Java Tutorial
🔍

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
  • final variables — 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.

Java
1int age; // declared, not yet initialized 2String name; // declared, not yet initialized 3double salary; // declared, not yet initialized

A 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.

Java
1int age = 25; // declared and initialized in one line 2String name = "Arjun"; // declared and initialized in one line 3double salary = 75000.50; // declared and initialized in one line

You can also declare first and initialize later:

Java
1int age; // declare 2age = 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:

Java
1int score; 2System.out.println(score); // ❌ error: variable score might not have been initialized 3 4int score = 0; 5System.out.println(score); // ✅ works fine

Variable Syntax — The Pattern

Every variable declaration follows the same pattern:

dataType variableName = value;
Java
1int age = 25; 2// ↑ ↑ ↑ 3// 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.

Java
1int score = 0; 2System.out.println(score); // 0 3 4score = 50; // update — no 'int' keyword 5System.out.println(score); // 50 6 7score = score + 10; // update using its own value 8System.out.println(score); // 60

⚠️ Common mistake: Writing the type again when updating:

Java
1int score = 0; 2int score = 50; // ❌ error: variable 'score' is already defined

The 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.

THREE TYPES OF VARIABLES IN JAVA Local Variable Declared inside a method Where: Inside method body Lifetime: Method starts → ends Default value: None — must initialize int x = 5; inside main() Instance Variable Declared inside class, outside method Where: Class body, outside methods Lifetime: Object created → destroyed Default value: Yes (0, false, null) String name; inside class body Static Variable Declared with static keyword Where: Class level with static Lifetime: Program starts → ends Default value: Yes (0, false, null) static int count; shared across all objects

1. Local Variables

Declared inside a method. They exist only while that method is running.

Java
1public static void main(String[] args) { 2 int age = 25; // local variable 3 String name = "Arjun"; // local variable 4 System.out.println(name + " is " + age); 5} 6// '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.

Java
1public class Student { 2 // Each Student object gets its OWN copy of these: 3 String name; 4 int age; 5 double gpa; 6 7 public static void main(String[] args) { 8 Student s1 = new Student(); 9 s1.name = "Priya"; 10 s1.gpa = 9.1; 11 12 Student s2 = new Student(); 13 s2.name = "Arjun"; 14 s2.gpa = 8.4; 15 16 System.out.println(s1.name + ": " + s1.gpa); // Priya: 9.1 17 System.out.println(s2.name + ": " + s2.gpa); // Arjun: 8.4 18 } 19}
  • Each object has its own copys1.name and s2.name are 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.

Java
1public class Student { 2 String name; // instance — each student has their own name 3 static int totalStudents = 0; // static — ONE shared count for all 4 5 public static void main(String[] args) { 6 Student s1 = new Student(); 7 s1.name = "Priya"; 8 totalStudents++; 9 10 Student s2 = new Student(); 11 s2.name = "Arjun"; 12 totalStudents++; 13 14 System.out.println("Total students: " + totalStudents); // 2 15 } 16}
  • 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.

Java
1public class ScopeDemo { 2 3 static int classLevel = 100; // accessible everywhere in this class 4 5 public static void main(String[] args) { 6 7 int methodLevel = 50; // accessible within main() 8 9 if (methodLevel > 10) { 10 int blockLevel = 20; // accessible ONLY inside this if-block 11 System.out.println(classLevel); // ✅ 100 12 System.out.println(methodLevel); // ✅ 50 13 System.out.println(blockLevel); // ✅ 20 14 } 15 16 System.out.println(classLevel); // ✅ 100 17 System.out.println(methodLevel); // ✅ 50 18 System.out.println(blockLevel); // ❌ error — blockLevel out of scope 19 } 20}

Loop variables are also scoped to the loop:

Java
1for (int i = 0; i < 5; i++) { 2 System.out.println(i); // ✅ i exists here 3} 4System.out.println(i); // ❌ error — i is gone after the loop ends

final Variables — Constants

Adding final to a variable means its value cannot be changed after initialization.

Java
1final int MAX_SCORE = 100; 2MAX_SCORE = 200; // ❌ error: cannot assign a value to final variable MAX_SCORE

By convention, final variables use UPPER_SNAKE_CASE:

Java
1final int MAX_SIZE = 50; 2final double TAX_RATE = 0.18; 3final String DEFAULT_COUNTRY = "India";

At the class level, static final creates a true program-wide constant:

Java
1public class Config { 2 static final int MAX_USERS = 1000; 3 static final String VERSION = "2.0"; 4}

A Complete Example

This program uses all three variable types together so you can see them side by side:

Java
1public class BankAccount { 2 3 String owner; // instance — each account has its own owner 4 double balance; // instance — each account has its own balance 5 static int totalAccounts = 0; // static — shared count across all accounts 6 static final double MIN_BALANCE = 500; // constant — never changes 7 8 public void deposit(double amount) { 9 double newBalance = balance + amount; // local — exists only in this method 10 balance = newBalance; 11 System.out.println("Deposited: ₹" + amount); 12 System.out.println("Balance: ₹" + balance); 13 } 14 15 public static void main(String[] args) { 16 BankAccount acc1 = new BankAccount(); 17 acc1.owner = "Priya"; 18 acc1.balance = 10000.0; 19 totalAccounts++; 20 21 BankAccount acc2 = new BankAccount(); 22 acc2.owner = "Arjun"; 23 acc2.balance = 25000.0; 24 totalAccounts++; 25 26 acc1.deposit(5000.0); 27 28 System.out.println("Owner: " + acc1.owner); 29 System.out.println("Minimum balance: ₹" + MIN_BALANCE); 30 System.out.println("Total accounts: " + totalAccounts); 31 } 32}

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.

Java
1var age = 25; // Java infers: int 2var name = "Arjun"; // Java infers: String 3var price = 99.99; // Java infers: double 4var isActive = true; // Java infers: boolean

var only works for local variables initialized at the point of declaration:

Java
1var score; // ❌ error — can't infer type without a value

Use var when the type is obvious from the right side. Spell it out when it isn't — readability comes first.

Common Mistakes — Quick Reference

MistakeBroken CodeFix
Using before declaringprintln(age); int age = 5;Declare before use
Using uninitialized localint x; println(x);Initialize: int x = 0;
Repeating type on updateint count = 0; int count = 1;count = 1; — no type
Accessing out of scopeif (...) { int x = 1; } println(x);Declare x before the if
Reassigning finalfinal int MAX = 10; MAX = 20;final values cannot change
Wrong type assignmentint age = "twenty";Match type: int age = 20;

The 3 Things to Remember From This Page

  1. Declare with type, update withoutint age = 25; to create, age = 30; to update. Writing the type again on update is a compile error.
  2. Local variables have no default — they must be initialized before use. Instance and static variables get automatic defaults (0, false, null).
  3. 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
  • final makes 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

TopicLink
Data types — what types variables can holdData Types →
Converting between typesType Casting →
Operators — using variables in expressionsOperators →
Getting user input into variablesUser Input (Scanner) →
Instance and static variables in depthClasses & Objects →
Variables | DevStackFlow