Java Variables
In this page:
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
int age = 25; // declaration and assignment combined
System.out.println(age);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
int x = 1, y = 2, z = 3;
System.out.println(x + " " + y + " " + z);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: