
Understanding variables in Java including primitive types, reference types, memory allocation, and scoping
Variables in Java are containers for storing data values. Understanding variables is fundamental to Java programming.
Java provides eight primitive data types for basic values:
Reference variables store addresses that point to objects in memory:
// Declaration
int age;
String name;
// Initialization
age = 25;
name = "Java Developer";
// Declaration and initialization
double salary = 75000.50;
boolean isActive = true;
char grade = 'A';
Variables have different scopes based on where they're declared:
public class Employee {
private String name; // Instance variable
private int age;
public Employee(String name, int age) {
this.name = name; // 'this' distinguishes from parameter
this.age = age;
}
}
public class Counter {
private static int count = 0; // Shared among all instances
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
public void calculate() {
int result = 0; // Local to this method
for (int i = 0; i < 10; i++) { // Loop variable
result += i;
}
// 'i' is not accessible here
}
public class MemoryExample {
public static void main(String[] args) {
int x = 10; // Stack
String name = "Java"; // Reference on stack, object on heap
int[] numbers = new int[100]; // Reference on stack, array on heap
}
}
customerAge instead of caUnderstanding variables and memory management is crucial for writing efficient and bug-free Java code.