← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 10 of 12

Java Variables

Variable Declaration

Declaring a variable (like int age;) reserves a slot in memory sized for its type, but that slot holds garbage or a default value until you actually assign something to it.

Example: Variable Declaration

java
public class Main {
	public static void main(String[] args) {
		int age; // declared - not yet assigned a meaningful value
		age = 25; // now assigned
		System.out.println(age);
	}
}

Variable Initialization

Combining declaration and assignment in one line, like int age = 25;, is the most common pattern and avoids the risk of accidentally using a variable before it's been given a meaningful value.

Example: Variable Initialization

java
public class Main {
	public static void main(String[] args) {
		int age = 25; // declaration and assignment combined
		System.out.println(age);
	}
}

Modifying Variables

Reassignment simply writes a new value into that same memory slot, as long as the new value's type matches (or can be automatically converted to) the variable's declared type.

Example: Modifying Variables

java
public class Main {
	public static void main(String[] args) {
		int age = 25;
		age = 26; // reassigned - new value must match the declared type
		System.out.println(age);
	}
}

Multiple Variables

Writing int x = 1, y = 2, z = 3; declares three separate int variables in one statement -- convenient for closely related values, though clarity often favors separate lines for unrelated ones.

Example: Multiple Variables

java
public class Main {
	public static void main(String[] args) {
		int x = 1, y = 2, z = 3;
		System.out.println(x + " " + y + " " + z);
	}
}

Variable Scope

Local variables live only inside the method or block where they're declared and vanish when it returns, while instance variables (declared at the class level) persist for the lifetime of the object and are visible to every method in that class.

Example: Variable Scope

java
public class Main {
	int instanceVar = 100; // lives as long as the object exists

	void showLocal() {
		int localVar = 5; // exists only inside this method
		System.out.println(localVar);
	}

	public static void main(String[] args) {
		new Main().showLocal();
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.