Java Variables
Learn what variables are in Java, how to declare and initialize them, variable types, scope, and naming conventions with examples.
Java VariablesLink to this section
Variables are used to store data values in a Java program. They act as containers that hold information which can be changed during program execution.
Understanding variables is fundamental because almost every Java program works with data stored in variables.
What is a Variable?Link to this section
A variable is a named memory location that stores a specific type of data. Each variable in Java must have a data type and a unique name.
note
Declaring Variables in JavaLink to this section
Variable declaration tells the compiler what type of data a variable will store.
Variables can be declared first and initialized later.
warning
Initializing VariablesLink to this section
Initialization means assigning a value to a variable.
Types of Variables in JavaLink to this section
Java variables are classified based on their scope and lifetime.
- Local Variables – Declared inside methods
- Instance Variables – Belong to an object
- Static Variables – Shared among all objects of a class
Local VariablesLink to this section
Local variables are declared inside methods or blocks and are accessible only within that block.
note
Instance VariablesLink to this section
Instance variables are declared inside a class but outside methods. Each object of the class gets its own copy.
Static VariablesLink to this section
Static variables are declared using the static keyword. They are shared among all instances of a class.
tip
Java Variable Naming RulesLink to this section
Java follows strict naming rules for variables:
- Must begin with a letter, underscore (_), or dollar sign ($)
- Cannot start with a number
- Cannot use Java reserved keywords
- Case-sensitive
warning
What is the main purpose of a variable in Java?
Java Variables
- Declare one variable of each primitive data type and print their values.
- Write a program that uses a static variable to count the number of objects created for a class.
- Create a class with two instance variables and display their values using an object.
- Declare a local variable inside a method and try accessing it outside the method. Observe the error.
- Rename poorly named variables in a sample program to meaningful names and explain the improvement.