Introduction
Variables are one of the most fundamental concepts in Java programming. They act as containers that store data values which can be used and manipulated throughout your program.
In this comprehensive guide, you'll learn everything about Java variables - from basic declaration to advanced concepts and best practices.
What are Variables?
Think of a variable as a labeled box that can hold a specific type of item. Just like you might have a box labeled "Photos" that can only hold photos, a Java variable has:
- A name (the label) - used to identify and access the variable
- A type (what kind of box) - determines what kind of data it can hold
- A value (the contents) - the actual data stored in the variable
Types of Variables in Java
Java has three types of variables based on their scope and lifetime:
1. Local Variables
Local variables are declared inside a method, constructor, or block. They exist only within that scope.
public class LocalVariableExample {
public static void main(String[] args) {
// Local variable - exists only within main method
int age = 25;
String name = "Rahul";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Output:
Name: Rahul
Age: 25
Key points about local variables:
- Must be initialized before use
- No default values
- Cannot use access modifiers (public, private)
- Destroyed when the method/block ends
2. Instance Variables
Instance variables are declared inside a class but outside any method. Each object has its own copy.
public class Student {
// Instance variables
String name;
int age;
double marks;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Marks: " + marks);
}
}public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Priya";
s1.age = 20;
s1.marks = 85.5;
s1.displayInfo();
}
}
Output:
Name: Priya
Age: 20
Marks: 85.5
Key points about instance variables:
- Have default values (0 for numbers, null for objects, false for boolean)
- Can use access modifiers
- Created when object is created, destroyed when object is garbage collected
3. Static (Class) Variables
Static variables belong to the class rather than instances. All objects share the same copy.
public class Counter {
// Static variable - shared by all objects
static int count = 0;
// Instance variable
String name;
Counter(String name) {
this.name = name;
count++; // Increment shared counter
}
static void showCount() {
System.out.println("Total objects created: " + count);
}
}public class Main {
public static void main(String[] args) {
Counter c1 = new Counter("First");
Counter c2 = new Counter("Second");
Counter c3 = new Counter("Third");
Counter.showCount();
}
}
Output:
Total objects created: 3
Variable Declaration and Initialization
Syntax
dataType variableName; // Declaration
variableName = value; // Initialization
dataType variableName = value; // Declaration + Initialization
Examples
public class VariableDeclaration {
public static void main(String[] args) {
// Integer types
int age = 25;
long population = 1400000000L;
// Floating point types
float price = 99.99f;
double pi = 3.14159265359;
// Character and Boolean
char grade = 'A';
boolean isStudent = true;
// String (reference type)
String name = "JavaCompiler.in";
// Multiple declarations
int a, b, c;
int x = 10, y = 20, z = 30;
System.out.println("Age: " + age);
System.out.println("Population: " + population);
System.out.println("Price: " + price);
System.out.println("Name: " + name);
}
}
Naming Conventions
Follow these Java naming conventions for variables:
studentName, totalAmount, isValid
- Bad: StudentName, total_amount, ISVALIDemployeeCount, averageScore
- Bad: x, temp, data final double PI = 3.14159;
final int MAX_SIZE = 100;
Best Practices
Common Mistakes to Avoid
int x;
System.out.println(x); // Compilation error!
int 1stNumber; // Can't start with number
int my-variable; // Can't use hyphens
int x = 3.14; // Error: can't assign double to int
Practice Problems
Try these exercises in our Java Compiler:
Summary
- Variables are containers for storing data values
- Three types: local, instance, and static variables
- Follow naming conventions for readable code
- Always initialize variables before using them
- Use appropriate data types for your needs
Frequently Asked Questions
What is a variable in Java?
A variable in Java is a container that holds data values. It has a name, a type, and a value. Variables allow you to store and manipulate data in your programs.
What are the types of variables in Java?
Java has three types of variables: local variables (declared inside methods), instance variables (declared inside a class but outside methods), and static/class variables (declared with the static keyword).
Can variable names start with numbers in Java?
No, variable names in Java cannot start with a number. They must start with a letter, underscore (_), or dollar sign ($). After the first character, they can contain numbers.
What is the difference between declaration and initialization?
Declaration is creating a variable with a name and type (e.g., int age;). Initialization is assigning a value to the variable (e.g., age = 25;). You can do both together: int age = 25;
Are Java variables case-sensitive?
Yes, Java variables are case-sensitive. This means "name", "Name", and "NAME" are three different variables.