Java Variables Tutorial: Declaration, Initialization, Scope, Types and Examples
Introduction
Java variables are one of the most fundamental concepts in Java programming. Programs need variables to store information such as names, ages, prices, salaries, account balances, and calculation results.
A variable is a named location associated with a value of a particular type. Depending on how a variable is declared, its value may be changed during program execution.
Understanding Java variables is essential before learning operators, control flow, methods, arrays, classes, objects, and object-oriented programming.
In this tutorial, you will learn:
- What a variable is in Java
- How to declare variables
- How to initialize variables
- Declaration vs initialization
- Variable scope
- Variable lifetime
- Local variables
- Instance variables
- Static variables
finalvariables- Constants
- Variable naming rules
- Java variable best practices
- Practical Java programs
- Practice exercises
Table of Contents
- What Is a Variable in Java?
- Java Variable Declaration
- Java Variable Initialization
- Declaration vs Initialization
- Variable Scope in Java
- Local Variables
- Instance Variables
- Static Variables
- Variable Lifetime
- Local vs Instance vs Static Variables
- Final Variables
- Constants in Java
- Java Variable Naming Rules
- Java Variable Best Practices
- Java Variable Examples
- Summary
- Practice Exercises
- Frequently Asked Questions
What Is a Variable in Java?
A variable is a named storage location used by a Java program to hold a value.
For example:
1int age = 22;
Here:
intis the data type.ageis the variable name.22is the value assigned to the variable.
The value of a non-final variable can generally be changed during program execution.
Example:
1int age = 22; 2 3age = 23; 4 5System.out.println(age);
Output:
123
Variables allow Java programs to store, calculate, and manipulate data.
Java Variable Declaration
Variable declaration means specifying the variable's type and name.
Syntax
1dataType variableName;
Examples
1int age; 2double price; 3char grade; 4boolean isStudent; 5String city;
At this point, these declarations introduce variables, but they do not assign explicit values to them.
For local variables, Java requires that a value be assigned before the variable is read.
Java Variable Initialization
Initialization means assigning an initial value to a variable.
Syntax
1dataType variableName = value;
Example
1int age = 22; 2double salary = 45000.50; 3String name = "Ankit"; 4boolean isJavaFun = true;
In these examples, the variables are declared and initialized in the same statement.
Multiple Variable Declarations
You can declare and initialize variables separately:
1int x = 10; 2int y = 20; 3int z = 30;
Java also allows multiple declarations of the same type in one statement:
1int x = 10, y = 20, z = 30;
For readability, declaring related variables separately is often preferable in larger programs.
Declaration vs Initialization
Declaration and initialization are different concepts.
Declaration
1int marks;
This declares a variable named marks.
Assignment
1marks = 95;
This assigns a value to the already-declared variable.
Declaration and Initialization Together
1int marks = 95;
This both declares and initializes the variable.
Example
1public class Example { 2 3 public static void main(String[] args) { 4 5 int marks; 6 7 marks = 95; 8 9 System.out.println(marks); 10 11 } 12 13}
Output:
195
Variable Scope in Java
Variable scope defines the part of the source code where a variable can be accessed.
Common variable categories include:
- Local variables
- Instance variables
- Static variables
The exact scope depends on where the variable is declared.
Local Scope
A local variable is accessible only within the method, constructor, or block where it is declared.
1public class Demo { 2 3 public static void main(String[] args) { 4 5 int number = 100; 6 7 System.out.println(number); 8 9 } 10 11}
The variable number is available inside the main() method but not outside its scope.
Block Scope
Variables declared inside a block are limited to that block.
1public class Demo { 2 3 public static void main(String[] args) { 4 5 if (true) { 6 7 int value = 100; 8 9 System.out.println(value); 10 } 11 12 // value cannot be accessed here 13 14 } 15 16}
This is important when working with if, for, while, and other blocks.
Local Variables in Java
A local variable is declared inside a method, constructor, or block.
Example:
1public class Test { 2 3 public static void main(String[] args) { 4 5 int age = 20; 6 7 System.out.println(age); 8 9 } 10 11}
Output:
120
Characteristics of Local Variables
Local variables:
- Exist within their declared scope.
- Must be definitely assigned before they are read.
- Do not receive automatic default values.
- Are commonly used for temporary calculations and method-specific data.
For example, this code is invalid:
1public class Test { 2 3 public static void main(String[] args) { 4 5 int age; 6 7 System.out.println(age); 8 9 } 10 11}
The compiler reports that the local variable may not have been initialized.
Instance Variables in Java
An instance variable is a non-static field declared inside a class.
Each object has its own instance fields.
Example:
1public class Student { 2 3 String name; 4 int age; 5 6 public static void main(String[] args) { 7 8 Student s1 = new Student(); 9 10 s1.name = "Rahul"; 11 s1.age = 21; 12 13 System.out.println(s1.name); 14 System.out.println(s1.age); 15 16 } 17 18}
Output:
1Rahul 221
Multiple Objects
Each object can have different instance-variable values.
1public class Student { 2 3 String name; 4 5 public static void main(String[] args) { 6 7 Student s1 = new Student(); 8 Student s2 = new Student(); 9 10 s1.name = "Rahul"; 11 s2.name = "Priya"; 12 13 System.out.println(s1.name); 14 System.out.println(s2.name); 15 16 } 17 18}
Output:
1Rahul 2Priya
The objects have separate name fields.
Default Values of Instance Variables
Instance fields receive default values when an object is created if no explicit initializer is provided.
Examples include:
| Type | Default Value |
|---|---|
int | 0 |
double | 0.0 |
char | '\u0000' |
boolean | false |
| Reference types | null |
Example:
1public class Student { 2 3 int age; 4 String name; 5 6 public static void main(String[] args) { 7 8 Student student = new Student(); 9 10 System.out.println(student.age); 11 System.out.println(student.name); 12 13 } 14 15}
Output:
10 2null
Static Variables in Java
A static variable is a class variable declared using the static keyword.
It belongs to the class rather than to a particular object.
Example:
1public class Student { 2 3 static String college = "Tech University"; 4 5 public static void main(String[] args) { 6 7 Student s1 = new Student(); 8 Student s2 = new Student(); 9 10 System.out.println(s1.college); 11 System.out.println(s2.college); 12 13 } 14 15}
Output:
1Tech University 2Tech University
The two objects access the same static field.
A clearer way to access a static variable is through the class name:
1System.out.println(Student.college);
When to Use Static Variables
Static variables are useful when one value logically belongs to the class and is shared among all instances.
For example:
1public class Employee { 2 3 static String companyName = "Tech Corp"; 4 5}
All Employee objects can share the same companyName.
Variable Lifetime in Java
Variable lifetime refers to how long a variable or field remains associated with a running program's execution and objects.
The lifetime depends on the kind of variable and the runtime context.
| Variable Type | General Lifetime |
|---|---|
| Local variable | During execution of its containing method or block, subject to language/runtime rules |
| Instance variable | As part of an object while that object is reachable and until it is reclaimed |
| Static variable | Associated with the class while its defining class remains loaded |
Garbage collection determines when unreachable objects and their instance fields can be reclaimed. Therefore, it is more accurate to avoid saying that an instance variable is always "destroyed immediately" when a method ends.
Local vs Instance vs Static Variables
The three common variable categories differ in scope, ownership, and initialization behavior.
| Feature | Local Variable | Instance Variable | Static Variable |
|---|---|---|---|
| Declared | Inside method, constructor, or block | Inside class, outside methods | Inside class with static |
| Belongs to | Method/block execution | Object | Class |
| Each object gets its own copy | No | Yes | No |
| Shared between objects | No | No | Yes |
| Automatic default value | No | Yes | Yes |
| Access | Within its scope | Through an object/reference | Preferably through class name |
| Typical use | Temporary calculations | Object-specific data | Class-wide shared data |
Example
1public class Employee { 2 3 static String company = "Tech Corp"; 4 5 String name; 6 7 public static void main(String[] args) { 8 9 Employee e1 = new Employee(); 10 Employee e2 = new Employee(); 11 12 e1.name = "Rahul"; 13 e2.name = "Priya"; 14 15 System.out.println(e1.name); 16 System.out.println(e2.name); 17 System.out.println(Employee.company); 18 19 } 20 21}
Here:
companyis a static variable shared by the class.nameis an instance variable with a separate value for each object.
Final Variables in Java
The final keyword prevents a variable from being assigned a new value after it has been initialized.
Example:
1final double PI = 3.14159; 2 3System.out.println(PI);
The following is not allowed:
1PI = 3.14;
This results in a compilation error because PI is a final variable.
Final Reference Variables
A final reference variable cannot be assigned to another object, but the object it references may still be mutable.
Example:
1final StringBuilder builder = new StringBuilder("Java"); 2 3builder.append(" Programming");
This is allowed because the reference still points to the same StringBuilder object.
However:
1builder = new StringBuilder("Python");
is not allowed because a final reference cannot be reassigned.
Therefore, final does not automatically make an object immutable.
Constants in Java
A constant is a value that is intended not to change.
Java does not have a separate constant keyword. Constants are commonly represented using static final fields.
Example:
1public class MathConstants { 2 3 public static final double PI = 3.141592653589793; 4 5}
Use the constant:
1System.out.println(MathConstants.PI);
Why Use static final?
staticmakes the field associated with the class.finalprevents reassignment.- Together, they are commonly used for class-level constants.
Java Constant Naming Convention
Constants are normally written using uppercase letters with underscores.
Examples:
1MAX_SIZE 2MIN_AGE 3DEFAULT_TIMEOUT 4PI 5MAX_CONNECTIONS
Java Variable Naming Rules
Java identifiers used for variables must follow the language's identifier rules.
A variable name:
- Cannot start with a number.
- Can start with a letter,
_, or$. - Can contain letters and digits.
- Cannot contain spaces.
- Cannot be a Java keyword.
- Is case-sensitive.
Valid Variable Names
1studentName 2totalMarks 3userAge 4salary 5_student 6$value
Invalid Variable Names
11student 2student-name 3student name 4class
For example:
1int studentAge = 20;
is valid.
This is invalid:
1int student age = 20;
because spaces cannot appear inside an identifier.
Although _ and $ are technically permitted in Java identifiers, ordinary application code generally uses descriptive names such as studentName instead.
Java Variable Naming Conventions
Java naming conventions improve readability and maintainability.
Variables
Use camelCase:
1studentName 2totalMarks 3accountBalance 4firstName
Classes
Use PascalCase:
1Student 2BankAccount 3Employee
Constants
Use UPPER_SNAKE_CASE:
1MAX_SIZE 2DEFAULT_TIMEOUT 3MINIMUM_BALANCE
Meaningful names are usually better than short names.
Prefer:
1double accountBalance; 2int totalStudents; 3String firstName;
instead of:
1double x; 2int a; 3String s;
Short names can still be appropriate for small, conventional contexts such as loop counters:
1for (int i = 0; i < 10; i++) { 2 System.out.println(i); 3}
Java Variable Best Practices
Follow these practices when working with variables:
Use Meaningful Names
Prefer:
1double accountBalance;
over:
1double x;
Keep Scope Small
Declare a variable as close as possible to where it is needed.
This improves readability and reduces accidental use.
Initialize Before Use
Make sure local variables have a value before reading them.
1int age = 20; 2 3System.out.println(age);
Use final When Appropriate
If a variable should not be reassigned, consider using final.
1final int MAX_USERS = 100;
Follow Java Naming Conventions
Use camelCase for variables:
1String firstName; 2int totalStudents; 3double accountBalance;
Avoid Unnecessary Global State
Keep shared mutable state limited when possible. Excessive use of static mutable variables can make applications harder to understand and test.
Practice Program: Java Variables
The following example demonstrates different types of variables:
1public class VariableExample { 2 3 static String company = "Tech Corp"; 4 5 String employeeName; 6 7 public static void main(String[] args) { 8 9 int employeeAge = 25; 10 11 VariableExample employee = new VariableExample(); 12 13 employee.employeeName = "Rahul"; 14 15 System.out.println("Name : " + employee.employeeName); 16 System.out.println("Age : " + employeeAge); 17 System.out.println("Company : " + VariableExample.company); 18 19 } 20 21}
Output:
1Name : Rahul 2Age : 25 3Company : Tech Corp
This example contains:
- A local variable:
employeeAge - An instance variable:
employeeName - A static variable:
company
Practice Program: Simple Calculator
The following program uses variables to perform arithmetic operations.
1public class Calculator { 2 3 public static void main(String[] args) { 4 5 int a = 20; 6 int b = 10; 7 8 System.out.println("Addition : " + (a + b)); 9 System.out.println("Subtraction : " + (a - b)); 10 System.out.println("Multiplication : " + (a * b)); 11 System.out.println("Division : " + (a / b)); 12 13 } 14 15}
Output:
1Addition : 30 2Subtraction : 10 3Multiplication : 200 4Division : 2
Here, a and b are local variables.
Practice Program: Circle Area
The following example uses a final variable for the value of π.
1public class AreaFinder { 2 3 public static void main(String[] args) { 4 5 final double PI = 3.14159; 6 7 double radius = 7; 8 9 double area = PI * radius * radius; 10 11 System.out.println("Radius : " + radius); 12 System.out.println("Area : " + area); 13 14 } 15 16}
Output:
1Radius : 7.0 2Area : 153.93791
Practice Program: Instance and Static Variables
This example demonstrates the difference between instance and static variables.
1public class Student { 2 3 String name; 4 5 static String college = "Tech University"; 6 7 public static void main(String[] args) { 8 9 Student s1 = new Student(); 10 Student s2 = new Student(); 11 12 s1.name = "Rahul"; 13 s2.name = "Priya"; 14 15 System.out.println(s1.name); 16 System.out.println(s2.name); 17 18 System.out.println(Student.college); 19 20 } 21 22}
Output:
1Rahul 2Priya 3Tech University
The name variable is different for each object, while college is shared by the class.
Summary
In this Java Variables tutorial, you learned:
- What variables are in Java
- How to declare variables
- How to initialize variables
- The difference between declaration and initialization
- Variable scope
- Local variables
- Instance variables
- Static variables
- Variable lifetime
- Differences between local, instance, and static variables
- The
finalkeyword - Constants using
static final - Java variable naming rules
- Java naming conventions
- Best practices for using variables
- Practical Java variable programs
Variables are a fundamental part of Java programming. Once you understand variables, you can move on to Java data types, operators, type casting, input, conditional statements, loops, methods, arrays, and object-oriented programming.
Practice Exercises
Exercise 1: Student Details
Create variables to store:
- Student name
- Roll number
- Age
- Percentage
Print all the details.
Exercise 2: Rectangle Area
Create variables for:
- Length
- Width
Calculate and print the area of the rectangle.
Exercise 3: Circle Circumference
Create a final constant for PI and calculate the circumference of a circle.
Formula:
1Circumference = 2 × PI × radius
Exercise 4: Company Information
Create a class containing:
- An instance variable for employee name
- A static variable for company name
- A final variable for the company's country
Print all three values.
Exercise 5: Variable Scope
Write a Java program that declares:
- A local variable inside
main() - An instance variable inside the class
- A static variable inside the class
Access each variable correctly and identify where each variable can be used.
Exercise 6: Final Variable
Create a final variable named MAX_SCORE with a value of 100.
Try to change its value and observe the compiler error.
Exercise 7: Multiple Objects
Create a Student class with:
1name 2age 3college
Make name and age instance variables and college a static variable.
Create two objects and give them different names and ages while keeping the same college.
Frequently Asked Questions
What is a variable in Java?
A variable is a named storage location associated with a value of a particular type. It allows a Java program to store and manipulate data.
What is variable declaration in Java?
Variable declaration specifies the variable's data type and name.
Example:
1int age;
What is variable initialization in Java?
Initialization means assigning an initial value to a variable.
Example:
1int age = 20;
What is a local variable in Java?
A local variable is declared inside a method, constructor, or block and can be accessed only within its scope.
What is an instance variable in Java?
An instance variable is a non-static field that belongs to an object. Each object normally has its own value for that field.
What is a static variable in Java?
A static variable is a class variable. It belongs to the class and is shared among instances of that class.
What is a final variable in Java?
A final variable cannot be assigned a new value after it has been initialized.
What is a constant in Java?
A Java constant is commonly represented by a static final field whose value is intended not to change.
What is the difference between local and instance variables?
A local variable belongs to a method, constructor, or block, while an instance variable belongs to an object.
What is the difference between static and instance variables?
An instance variable has a separate value for each object, while a static variable belongs to the class and is shared among its instances.