Java Notes
Complete guide to Java variables — declaration, initialization, types of variables (local, instance, static), scope, naming conventions, and memory allocation with practical examples.
A variable is a named container that stores data in memory. In Java, every variable has a specific type that determines what values it can hold and how much memory it occupies.
What is a Variable?
Think of a variable as a labeled box in memory:
public class VariableBasics {
public static void main(String[] args) {
// Declaration: telling Java "reserve space for this type"
int age;
// Initialization: putting a value in that space
age = 25;
// Declaration + Initialization (most common)
String name = "Alice";
double salary = 75000.50;
boolean isActive = true;
// Using variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Active: " + isActive);
// Reassignment (changing the value)
age = 26;
System.out.println("Next year age: " + age);
}
}Name: Alice Age: 25 Salary: $75000.5 Active: true Next year age: 26
Variable Declaration Syntax
// Syntax: type variableName = value;
// Single declaration
int count = 0;
// Multiple declarations of same type
int x = 1, y = 2, z = 3;
// Declaration without initialization (gets default value or compile error)
int uninitialized; // OK for instance/static fields; ERROR for local variables
// Constants (cannot be reassigned)
final double PI = 3.14159265358979;
final String APP_NAME = "MyApp";
// PI = 3.14; // COMPILE ERROR: cannot assign to final variableThree Types of Variables
Java has three categories of variables based on where they're declared:
1. Local Variables
Declared inside a method, constructor, or block. They exist only within that scope:
Hello 0 Hello 1 Hello 2 x = 10
Local variable rules:
- No default values — must be initialized before use
- No access modifiers (public, private, etc.)
- Stored on the stack (fast allocation/deallocation)
- Created when method is called, destroyed when method returns
- Not visible outside their block
{}
2. Instance Variables (Non-static Fields)
Declared inside a class but outside methods. Each object gets its own copy:
public class InstanceVariableDemo {
// Instance variables — each object has its own copy
String name; // default: null
int age; // default: 0
double balance; // default: 0.0
boolean isVerified; // default: false
// Constructor uses instance variables
public InstanceVariableDemo(String name, int age) {
this.name = name; // 'this' distinguishes instance from parameter
this.age = age;
}
public void display() {
// Instance variables accessible in any method of the class
System.out.println(name + ", age " + age +
", balance: " + balance + ", verified: " + isVerified);
}
public static void main(String[] args) {
// Each object has independent instance variables
InstanceVariableDemo person1 = new InstanceVariableDemo("Alice", 30);
InstanceVariableDemo person2 = new InstanceVariableDemo("Bob", 25);
person1.balance = 5000;
person2.balance = 3000;
person1.isVerified = true;
person1.display();
person2.display();
}
}Alice, age 30, balance: 5000.0, verified: true Bob, age 25, balance: 3000.0, verified: false
Instance variable rules:
- Have default values (0, 0.0, false, null)
- Can have access modifiers (private, public, protected)
- Stored on the heap (part of the object)
- Created when object is instantiated (
new), destroyed when object is garbage collected - Accessible by all methods in the class via
this
3. Static (Class) Variables
Declared with the static keyword. One copy shared among all objects:
ID: 1, Name: Alice (Total: 3 at Tech Academy) ID: 2, Name: Bob (Total: 3 at Tech Academy) ID: 3, Name: Charlie (Total: 3 at Tech Academy) Total enrolled: 3
Static variable rules:
- One copy in memory (in Method Area), shared by all instances
- Accessed via
ClassName.variable(preferred) or via an object - Created when the class is loaded, destroyed when class is unloaded
- Can be accessed from static methods without an object
Variable Comparison Table
| Feature | Local | Instance | Static |
|---|---|---|---|
| Declared in | Method/block | Class (outside methods) | Class with static |
| Default value | None (must initialize) | Yes (0, null, false) | Yes (0, null, false) |
| Memory | Stack | Heap (in object) | Method Area |
| Lifetime | Method execution | Object lifetime | Class lifetime |
| Access modifiers | No | Yes | Yes |
| Per-object copy | N/A | Yes | No (shared) |
| Access via | Direct name | this.name / object | ClassName.name |
The var Keyword (Java 10+)
Java 10 introduced local variable type inference:
public class VarDemo {
public static void main(String[] args) {
// Instead of explicit type:
String message1 = "Hello";
ArrayList<String> list1 = new ArrayList<String>();
// Use var (compiler infers the type):
var message2 = "Hello"; // inferred as String
var list2 = new ArrayList<String>(); // inferred as ArrayList<String>
var number = 42; // inferred as int
var pi = 3.14; // inferred as double
// var is still strongly typed!
// number = "text"; // ERROR: incompatible types
System.out.println("message2 type: " + message2.getClass().getSimpleName());
System.out.println("list2 type: " + list2.getClass().getSimpleName());
// var works great in for loops
var names = List.of("Alice", "Bob", "Charlie");
for (var name : names) {
System.out.println("Hello, " + name);
}
}
}message2 type: String list2 type: ArrayList Hello, Alice Hello, Bob Hello, Charlie
var limitations:
- Only for local variables (not fields, parameters, or return types)
- Must be initialized on the same line
- Cannot be initialized with
nullalone (var x = null;— what type?) - Not a keyword — it's a "reserved type name" (
varcan still be a variable name in old code)
Variable Scope and Lifetime
Class level: 100 Method level: 300 Block level: 400 Loop: i=0, loopVar=0 Loop: i=1, loopVar=10 Loop: i=2, loopVar=20
Variable Naming Conventions
public class NamingConventions {
// CONSTANTS: ALL_UPPER_CASE with underscores
static final int MAX_SIZE = 100;
static final String DB_URL = "localhost:5432";
// Instance/local variables: camelCase
private String firstName;
private int accountBalance;
private boolean isLoggedIn;
// BAD names (avoid these):
// int x; // meaningless
// String s; // too short
// int data; // too vague
// int temp; // unclear purpose
// int a1, a2, a3; // numbered variables = bad design
// GOOD names:
// int studentAge;
// String emailAddress;
// double totalRevenue;
// boolean hasPermission;
public static void main(String[] args) {
// Variable names can contain: letters, digits, _, $
int _count = 1; // valid (but avoid leading _)
int $price = 99; // valid (but avoid $)
int age2 = 20; // valid
// int 2age = 20; // INVALID: can't start with digit
// int my-var = 5; // INVALID: no hyphens
// int class = 1; // INVALID: 'class' is a keyword
System.out.println("Valid names: " + _count + ", " + $price + ", " + age2);
}
}Valid names: 1, 99, 20
Default Values
byte: 0 short: 0 int: 0 long: 0 float: 0.0 double: 0.0 char: [ ] (unicode 0) boolean: false String: null array: null
Common Mistakes
- Using a local variable before initialization — Java doesn't give local variables default values. You MUST assign a value before reading.
- Shadowing instance variables — if a method parameter has the same name as a field, use
this.fieldNameto access the field. - Confusing
=(assignment) with==(comparison) —if (x = 5)is an assignment, not a comparison (won't compile for int, but dangerous with boolean). - Thinking
varmakes Java dynamically typed —varis type inference at compile time. The type is fixed once inferred. - Using static variables as instance variables — static variables are shared. Changing one affects all objects.
- Declaring variables too broadly — declare variables in the narrowest scope possible for clarity and memory efficiency.
Interview Questions
Q1: What are the differences between local, instance, and static variables?
Answer: Local variables are declared in methods, have no default values, exist only during method execution, and are stored on the stack. Instance variables are declared in a class, have default values, exist as long as the object exists, and are stored on the heap. Static variables are declared with static, have default values, exist for the class's lifetime, and are shared among all instances (stored in the Method Area).
Q2: Can you use a local variable without initializing it?
Answer: No. Java requires local variables to be definitely assigned before use. The compiler performs flow analysis and rejects code where a local variable might be read before being written. Instance and static variables get default values automatically, but local variables do not.
Q3: What is variable shadowing?
Answer: Variable shadowing occurs when a local variable or parameter has the same name as an instance variable. The local variable "shadows" (hides) the instance variable within that scope. To access the instance variable, use this.variableName. Example: in a constructor, this.name = name; distinguishes the field from the parameter.
Q4: What is the difference between final variable and static final variable?
Answer: A final instance variable is a constant per object — each object can have a different value, but once set (in constructor or declaration), it cannot be changed. A static final variable is a class-level constant — one value shared by all instances, set at declaration or in a static block, and never changed. static final is Java's equivalent of a global constant.
Q5: Explain the var keyword introduced in Java 10.
Answer: var enables local variable type inference — the compiler determines the type from the right-hand side of the assignment. It reduces verbosity (e.g., var list = new ArrayList<String>() instead of repeating the type). Important: var only works for local variables with initializers, not for fields, method parameters, or return types. It's still statically typed — the type is fixed at compile time.
Summary
Variables in Java are strongly typed containers for data. Understanding the three types (local, instance, static), their default values, scope rules, and memory locations is fundamental to writing correct Java programs. Use meaningful names in camelCase, declare variables in the narrowest scope possible, and remember that local variables must always be explicitly initialized before use.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Variables in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, syntax, basics
Related Java Master Course Topics