Introduction
A variable is a named storage location in memory that holds a value. Think of it as a container with a label that can store data. The data stored in a variable can be changed during program execution (hence the name “variable”).
Why Variables?
- Store Data: Hold values for processing
- Reusability: Use the same value multiple times
- Readability: Give meaningful names to values
- Flexibility: Change values during execution
Variable Declaration
Syntax:
type variableName;
Examples:
int age;
double salary;
char grade;
boolean isStudent;
String name;
Variable Initialization
Syntax:
variableName = value;
Examples:
age = 25;
salary = 50000.50;
grade = 'A';
isStudent = true;
name = "John";
Declaration + Initialization (Combined)
Syntax:
type variableName = value;
Examples:
int age = 25;
double salary = 50000.50;
char grade = 'A';
boolean isStudent = true;
String name = "John";
Multiple Variable Declaration
Same Type:
// Method 1: Separate lines
int x;
int y;
int z;
// Method 2: Single line (same type)
int x, y, z;
// Method 3: With initialization
int x = 10, y = 20, z = 30;
// Method 4: Mixed initialization
int a = 5, b, c = 10;
Example:
// Multiple variables
int length, width, height;
length = 10;
width = 5;
height = 3;
// Or combined
int length = 10, width = 5, height = 3;
Variable Naming Rules
Must Follow:
- Can contain: Letters, digits, underscore (_), dollar sign ($)
- Must start with: Letter, underscore (_), or dollar sign ($)
- Cannot start with: Digit
- Cannot be: Java keyword
- Case-sensitive:
age≠Age≠AGE - No spaces: Use camelCase instead
- No special characters: Except _ and $
Valid Variable Names:
int age; // ✓ Good
int studentAge; // ✓ Good (camelCase)
int student_age; // ✓ Valid (but not Java convention)
int _temp; // ✓ Valid
int $price; // ✓ Valid
int age2; // ✓ Valid
int firstName; // ✓ Good
int firstNameOfStudent; // ✓ Valid but long
Invalid Variable Names:
int 2age; // ❌ Starts with digit
int first-name; // ❌ Contains hyphen
int first name; // ❌ Contains space
int int; // ❌ Java keyword
int class; // ❌ Java keyword
int @value; // ❌ Contains @
int first.name; // ❌ Contains dot
Variable Naming Conventions
Best Practices:
1. Use Meaningful Names:
// Bad
int a, b, c;
// Good
int age, salary, count;
2. Use camelCase:
// Correct
int studentAge;
String firstName;
double accountBalance;
// Wrong (don't use in Java)
int student_age; // snake_case (Python style)
int StudentAge; // PascalCase (for classes only)
3. Start with Lowercase:
int age; // ✓ Correct
int Age; // ❌ Incorrect (looks like class)
4. Be Descriptive:
// Bad
int n;
// Good
int numberOfStudents;
5. Boolean Variables:
// Use is, has, can prefix
boolean isStudent;
boolean hasLicense;
boolean canVote;
boolean isValid;
6. Constants (Final Variables):
// Use ALL_CAPS with underscores
final int MAX_VALUE = 100;
final double PI = 3.14159;
final String DEFAULT_NAME = "Guest";
Types of Variables
Java has three types of variables:
1. Local Variables
Definition: Variables declared inside a method, constructor, or block.
Characteristics:
- Must be initialized before use
- No default value
- Scope: Only within the method/block
- Cannot use access modifiers (public, private)
- Destroyed when method ends
Example:
public class Demo {
public void display() {
int x = 10; // Local variable
String name = "John"; // Local variable
System.out.println(x); // ✓ Works
System.out.println(name); // ✓ Works
}
public void show() {
System.out.println(x); // ❌ Error: x not accessible here
}
}
Important:
public void method() {
int x; // Declared but not initialized
System.out.println(x); // ❌ Error: variable not initialized
int y = 10; // Declared and initialized
System.out.println(y); // ✓ Works
}
2. Instance Variables (Non-Static Fields)
Definition: Variables declared in a class but outside any method.
Characteristics:
- Belong to an object (instance)
- Have default values
- Created when object is created
- Destroyed when object is destroyed
- Can use access modifiers
- Each object has its own copy
Example:
public class Student {
// Instance variables
String name; // Default: null
int age; // Default: 0
double marks; // Default: 0.0
boolean isActive; // Default: false
public void display() {
System.out.println(name); // ✓ Accessible
System.out.println(age); // ✓ Accessible
}
}
// Using instance variables
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Alice";
s1.age = 20;
Student s2 = new Student();
s2.name = "Bob";
s2.age = 22;
// Each object has its own copy
System.out.println(s1.name); // Alice
System.out.println(s2.name); // Bob
}
}
Default Values:
public class Demo {
int x; // 0
double y; // 0.0
boolean z; // false
char c; // '\u0000'
String s; // null
public void show() {
System.out.println(x); // 0 (not error, has default)
}
}
3. Class Variables (Static Fields)
Definition: Variables declared with static keyword.
Characteristics:
- Belong to the class, not objects
- Only one copy shared by all objects
- Created when class is loaded
- Destroyed when program ends
- Accessed using class name
- Have default values
Example:
public class Counter {
static int count = 0; // Class variable (shared)
String name; // Instance variable (separate)
public Counter(String n) {
name = n;
count++; // Increments for all objects
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter("First");
Counter c2 = new Counter("Second");
Counter c3 = new Counter("Third");
// Static variable shared by all
System.out.println(Counter.count); // 3
System.out.println(c1.count); // 3 (also works but not recommended)
}
}
Best Practice:
// Access static variables using class name
Counter.count // ✓ Recommended
c1.count // ✓ Works but not recommended
Comparison of Variable Types
| Feature | Local | Instance | Static |
|---|---|---|---|
| Declaration | Inside method | In class, outside method | With static keyword |
| Scope | Method/block | Object | Class |
| Default Value | No | Yes | Yes |
| Initialization | Required | Optional | Optional |
| Access Modifier | No | Yes | Yes |
| Memory | Stack | Heap | Method Area |
| Lifetime | Until method ends | Until object exists | Until program ends |
| Copies | Each call | Each object | One for all |
Example:
public class Example {
// Static variable (class variable)
static int classVar = 100;
// Instance variable
int instanceVar = 50;
public void method() {
// Local variable
int localVar = 10;
System.out.println(classVar); // ✓ Accessible
System.out.println(instanceVar); // ✓ Accessible
System.out.println(localVar); // ✓ Accessible
}
public void anotherMethod() {
System.out.println(classVar); // ✓ Accessible
System.out.println(instanceVar); // ✓ Accessible
System.out.println(localVar); // ❌ Error: not accessible
}
}
Final Variables (Constants)
Definition: Variables that cannot be changed after initialization.
Syntax:
final type VARIABLE_NAME = value;
Examples:
// Constant values
final int MAX_AGE = 100;
final double PI = 3.14159;
final String COLLEGE_NAME = "ABC College";
// Cannot change
MAX_AGE = 200; // ❌ Error: cannot assign value to final variable
Naming Convention:
- Use ALL_CAPS
- Separate words with underscores
final int MAX_VALUE = 100;
final int MIN_VALUE = 0;
final double TAX_RATE = 0.18;
final String DEFAULT_COLOR = "Blue";
Usage:
public class Circle {
final double PI = 3.14159; // Constant
public double area(double radius) {
return PI * radius * radius;
}
}
Variable Scope
Scope: The region where a variable is accessible.
1. Method Scope:
public void method() {
int x = 10; // Scope: only inside this method
if (x > 5) {
int y = 20; // Scope: only inside this if block
System.out.println(x); // ✓ Accessible
System.out.println(y); // ✓ Accessible
}
System.out.println(x); // ✓ Accessible
System.out.println(y); // ❌ Error: y not accessible outside if
}
2. Block Scope:
public void method() {
int x = 10;
{
int y = 20; // Block scope
System.out.println(x); // ✓ Accessible
System.out.println(y); // ✓ Accessible
}
System.out.println(x); // ✓ Accessible
System.out.println(y); // ❌ Error: y out of scope
}
3. Class Scope:
public class Demo {
int x = 10; // Class scope (instance variable)
public void method1() {
System.out.println(x); // ✓ Accessible
}
public void method2() {
System.out.println(x); // ✓ Accessible
}
}
Variable Shadowing
Definition: When a local variable has the same name as an instance variable.
public class Demo {
int x = 10; // Instance variable
public void method() {
int x = 20; // Local variable (shadows instance variable)
System.out.println(x); // 20 (local)
System.out.println(this.x); // 10 (instance)
}
}
Using this keyword:
public class Student {
String name; // Instance variable
public void setName(String name) { // Parameter has same name
this.name = name; // this.name refers to instance variable
// name alone refers to parameter
}
}
Default Values
Instance and Static Variables have default values:
| Type | Default Value |
|---|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0 |
| char | ’\u0000’ |
| boolean | false |
| Reference | null |
Local Variables do NOT have default values:
public void method() {
int x;
System.out.println(x); // ❌ Error: variable not initialized
}
Common Errors
1. Uninitialized Local Variable:
public void method() {
int x;
System.out.println(x); // ❌ Error
int y = 10;
System.out.println(y); // ✓ OK
}
2. Variable Already Defined:
public void method() {
int x = 10;
int x = 20; // ❌ Error: variable x is already defined
}
3. Variable Not in Scope:
if (true) {
int x = 10;
}
System.out.println(x); // ❌ Error: x out of scope
4. Final Variable Reassignment:
final int x = 10;
x = 20; // ❌ Error: cannot assign value to final variable
Best Practices
- Use meaningful names:
studentAgenotsa - Follow camelCase:
firstNamenotfirstname - Initialize local variables: Before using them
- Use constants for fixed values:
final int MAX_SIZE = 100 - Minimize scope: Declare variables in smallest scope needed
- One purpose per variable: Don’t reuse for different purposes
- Avoid magic numbers: Use named constants instead
// Bad
int total = price * 1.18;
// Good
final double TAX_RATE = 0.18;
int total = price * (1 + TAX_RATE);
Exam Tips
Remember:
- Variable Types: Local, Instance, Static
- Local variables: No default value, must initialize
- Instance variables: Have default values, one per object
- Static variables: Shared by all objects, one copy
- final: Makes variable constant
- Naming: camelCase for variables, ALL_CAPS for constants
- Scope: Where variable is accessible
- this: Refers to current object’s instance variable
Common Questions:
- What are different types of variables?
- Difference between instance and static variables
- What is variable scope?
- Do local variables have default values?
- What is the use of final keyword?
- Explain variable shadowing
- What is this keyword?
- What are naming conventions for variables?