In Java programming, a variable is a container that stores a value while your program is running. Suppose you have a labelled box that has a name (variable name) and holds a certain type of data, such as:
- Numbers (10, 3.14)
- Text or characters (“Hello” or ‘A’)
- True/false values (true or false)
Every variable in Java has a specific data type, and that data type tells Java what kind of values the variable can store.
For example:
int age = 25; // Stores whole number
double price = 19.99; // Stores decimal number
char grade = 'A'; // Stores a single letter
boolean isJavaFun = true; // Stores true or false
Why are Variables Important?
Variables are important in Java and also in other programming.
- It allows you to store changing data while the program is running. For example, a game score keeps increasing while running.
- Variables make our code flexible and reusable. Means you can write one piece of code and use different values without rewriting everything.
- It can also help to break big problems into smaller steps. For example, we can store results in variables and use them later instead of doing the same calculation again.
int a = 5;
int b = 10;
int sum = a + b; // Stores the result for later use
System.out.println(sum); // Prints 15
See this example, it has store the result for later use.
How To Declare a Variable in Java
First, we are creating a place in memory to store data, and giving that place a name so you can use it later.
Syntax of the variable:
type variableName = value;
Basic example:
int age = 25; // Declaring and initializing an integer variable
Explanation:
- int refers to data type of variable.
- age is the name of the variable (your label for that memory space).
- 25 is the value you’re putting inside it (initializing the variable).
Types of Variables in Java
Java supports three main types of variables, such as:
- Local Variables
- Instance Variables
- Static Variables (Class Variables)
1) Local Variables
- A local variable can only be used inside the method, loop, or block where you wrote it. The program won’t run outside of it.
Example:
public class LocalVariableDemo {
public static void main(String[] args) {
int age = 25; // Local variable
System.out.println("My age is: " + age);
}
}
Output:
My age is: 25
See this code, we have created an age inside the main method. It can not be accessed outside this method
2) Instance Variables
- An instance means we can write them directly inside the class body, not inside a method or loop.
- It has default values like 0 for numbers and null for objects.
For example:
public class InstanceVariableDemo {
String city; // Instance variable
public static void main(String[] args) {
InstanceVariableDemo obj = new InstanceVariableDemo();
obj.city = "Delhi";
System.out.println("City name: " + obj.city);
}
}
Output:
City name: Delhi
In this code, the city is tied to the object obj. If you create another object, it will have its separate city value.
3) Static Variables (Class Variables)
- These variables are declared with the static keyword inside a class but outside a method. For example:
Example:
public class StaticVariableDemo {
static String course = "Java Programming"; // Static variable
public static void main(String[] args) {
System.out.println("Course Name: " + course);
}
}
Output:
Course Name: Java Programming
In this code, Course is static, so every object of StaticVariableDemo will share he same value. We don’t need an object to access it; we can call it directly using the class name.
What is Static Keyword in Java?
The static keyword in Java means that the member (variable, method, or block) belongs to the class itself, not to any specific object of the class.
- Without static, each object gets its separate copy.
- With static, all objects share one single copy.
1) Static Variable
This refers to one copy for the whole class, no matter how many objects you create.
- All objects share he same value.
- If one object changes it, then all objects see the new class.
For example:
class Counter {
static int count = 0; // Shared by all
Counter() {
count++;
}
}
public class Test {
public static void main(String[] args) {
Counter c1 = new Counter(); // count becomes 1
Counter c2 = new Counter(); // count becomes 2
System.out.println(Counter.count); // Prints: 2
}
}
It means both c1 and c2 share the same count.
2) Static Method
You can use a static method without creating an object.
- It’s called using ClassName.methodName().
- You cannot use non-static (instance) variables directly, because non-static variables need an object.
For example:
class MathUtils {
static int square(int x) {
return x * x;
}
}
public class Test {
public static void main(String[] args) {
System.out.println(MathUtils.square(5)); // Prints: 25
}
}
See this code, you don’t need an object, call it directly from the class.
3) Static Block
Static block runs only once, when the class is loaded into memory, before the main() method runs. It is useful for setting up static variables.
For example:
class Example {
static int value;
static {
value = 10; // This runs before anything else
System.out.println("Static block executed");
}
}
public class Test {
public static void main(String[] args) {
System.out.println(Example.value);
}
}
In this example:
- when you first use the Example class, Java loads it into memory.
- The static block runs immediately, even before the main() method.
- It sets up the value and prints the message.
Rules for Naming Variables
Now, understand some variable rules that can help you in your project.
1) Variable names must start with a letter, $, or Underscore ( _ ).
- You can write variables like this: name, _count, $value
- Not allowed like 1count (Means it cannot start with a number)
2) Variable names are case-sensitive
- Age and age are two different variables in Java.
- For example
int Age = 25;
int age = 30;
System.out.println(Age); // 25
System.out.println(age); // 30
- Java think both variables differently.
3) Avoid using reserved keywords
- We can’t use Java reserved keywords (like class, int, static) as a variable name. Because Java uses those keywords for its meaning.
- For example
int class = 5; // Error: 'class' is reserved
- It is possible if you write like _count, $var, myVar.
What is the final Keyword in Java?
In Java, final means “unchangeable” or “constant”. Once you give a value to a final variable, you cannot change it later.
It’s like writing something in permanent ink that you can read, but you can’t erase or rewrite it.
How to use Final keyword with Variables?
Once you decide a variable should be final, Java needs to know its value immediately when it’s created, or at least before it’s first used.
Case 1: Initialize when declaring
final int marks = 100; // value fixed now
Here, you gave marks a value at the same time you declared it. marks will always be 100 in the program.
Case 2: Initialize inside a constructor (for instance variables)
class Student {
final int rollNumber;
Student(int rn) {
rollNumber = rn;
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(5);
Student s2 = new Student(10);
System.out.println("Roll number of s1: " + s1.rollNumber);
System.out.println("Roll number of s2: " + s2.rollNumber);
}
}
Output:
Roll number of s1: 5
Roll number of s2: 10
Here, each object gets its final variable value, set only once in the constructor.
Lunch Box Example
Now, we will create a mini project that you can easily understand about variables. Think of a variable as a lunch box in which you store food like this:
- The lunch box decides what can be stored (only rice, only juice, only chapati, etc.).
- The name of the lunch box is your label, so you know which one is yours.
- value is the food you keep inside.
Java Example:
class LunchBoxDemo {
public static void main(String[] args) {
// Declaring and initializing variables (like lunch boxes with food)
String lunchBoxOwner = "Riya"; // Name label on lunch box
String foodInside = "Pasta"; // What's inside the lunch box
int quantity = 2; // Number of pasta boxes
// Displaying the lunch box info
System.out.println(lunchBoxOwner + "'s lunch box has " + quantity + " " + foodInside + " servings.");
// Changing the value inside the variable (like changing food)
foodInside = "Sandwich";
quantity = 1;
System.out.println(lunchBoxOwner + " changed the food to " + quantity + " " + foodInside + ".");
}
}
Output of this program:
Riya's lunch box has 2 Pasta servings.
Riya changed the food to 1 Sandwich.
Code explanation:
- String lunchBoxOwner = “Riya”; → It is the label who owns the lunch box.
- String foodInside = “Pasta”; → It is the actual content.
- int quantity = 2; → This number shows the quantity.
- You can change the value inside a variable anytime.
Exercise For Practice
Create small project: My Savings Tracker
Your Task:
Building a small program that tracks how much money you have saved.
The program should take the following steps:
- Store the owner’s name (String).
- Store the total savings amount (double).
- Store the currency type (String).
- Print a sentence showing the savings.
- Increase the savings by a certain amount and print the updated details again.
Rules:
- Use meaningful variable names.
- Write comments explaining which part of the example matches which variable.
- Values should be changeable (no final).
Your output should look like this (You can use your values).
Peter has saved 1500.5 INR.
Peter's savings increased to 2000.5 INR after adding more money.
Try this project by yourself without taking helps.
Learn Further Topics:
- How we can use Variables in Java?
- How we can use Operators in Java?
- What are the Strings in Java?
- What are the Methods in Java?

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.