Variables in Java
In real life, we store information so we can reuse it later. For example, we remember a person’s name, age, or salary instead of calculating it again and again.
In Java, this stored information is kept using variables. A variable acts like a labeled container that holds a value in memory.
Why Variables Are Important
Without variables, programs would not be practical. Every calculation, decision, and output in a Java program depends on variables.
Variables allow programs to work with changing data, such as user input, calculations, or results from databases.
In large applications, variables help organize data clearly and make code easier to understand and maintain.
How Variables Work in Java
Before using a variable, Java needs two things:
- The type of data it will store
- The name of the variable
This tells Java how much memory to allocate and how the value should behave.
Declaring and Assigning Variables
Let’s look at a simple example where we store basic information about a student using variables.
public class VariablesExample {
public static void main(String[] args) {
int age = 20;
double percentage = 85.6;
char grade = 'A';
boolean isPassed = true;
System.out.println(age);
System.out.println(percentage);
System.out.println(grade);
System.out.println(isPassed);
}
}
Each variable stores a different type of data, and Java handles each one according to its data type.
Variable Naming Rules
Java follows strict rules when naming variables. Following these rules helps avoid errors and improves readability.
- Variable names must start with a letter, underscore, or dollar sign
- They cannot start with a number
- Spaces are not allowed
- Java keywords cannot be used as variable names
Java is case-sensitive, so age and Age are treated as different variables.
Good Variable Naming Practices
Beyond rules, Java developers follow conventions to write clean code.
Variable names should be meaningful and easy to understand. Instead of short or unclear names, use descriptive ones.
- Use
studentAgeinstead ofa - Use
totalMarksinstead oftm - Use camelCase for multi-word names
Variables Change During Program Execution
One important feature of variables is that their values can change. This allows Java programs to react to user input and calculations.
For example, a bank balance variable changes whenever money is deposited or withdrawn.
What You Learned in This Lesson
- What variables are and why they are needed
- How to declare and assign variables in Java
- Variable naming rules and best practices
- How variables help programs work with changing data
In the next lesson, you will learn about operators, which allow Java programs to perform calculations and comparisons using variables.