Java Basics
Variables in Java
A variable is a named storage location associated with a type. Variables allow a Java program to retain values, read them later, and—unless restricted—assign new values while the program runs.
Quick answer
What is a variable in Java?
A Java variable is a named storage location associated with a declared type. For example, int age = 25; declares an integer variable named age and initializes it with 25.
What you will learn
- How to declare, initialize, read, and update variables.
- The differences among local variables, instance fields, and static fields.
- How scope and lifetime control where a variable can be used.
- Which variables receive default values.
- How
finalcreates a non-reassignable variable.
Before you begin
Review Java Keywords. Variable names are identifiers, so reserved keywords cannot be used as variable names.
Variable declaration and initialization
A declaration provides the variable's type and identifier. An initializer supplies its first value.
DataType identifier = value;public class VariableDeclaration {
public static void main(String[] args) {
int age = 25;
double price = 49.99;
String course = "Java";
boolean available = true;
System.out.println(course + " age value: " + age);
}
}Reading and updating a variable
Use the identifier to read the stored value. An assignment statement can replace the value when the variable is not final.
int score = 10;
score = 20;
System.out.println(score); // 20Types of variables in Java
| Kind | Declared where? | Owned by | Default value? |
|---|---|---|---|
| Local variable | Inside a method, constructor, or block | The executing block or method | No |
| Instance variable | In a class, outside methods, without static | Each object | Yes |
| Static variable | In a class with static | The class | Yes |
| Parameter | In a method, constructor, or lambda parameter list | The invocation | Supplied by the caller |
Local variables
A local variable exists within the method, constructor, or block where it is declared. Java requires definite assignment before the value is read.
Instance variables
An instance variable, also called a non-static field, belongs to an object. Every object receives its own copy.
Static variables
A static field belongs to the class. One class-level value is shared by all instances loaded by the same class loader.
Important rule for static variables
Static variables cannot be local. Since only one copy exists per class, changing it affects all objects.
public class VariableKinds {
int instanceValue = 50; // instance variable
static int sharedValue = 100; // static variable
void showValues(int parameterValue) { // parameter
int localValue = 150; // local variable
System.out.println(instanceValue);
System.out.println(sharedValue);
System.out.println(parameterValue);
System.out.println(localValue);
}
public static void main(String[] args) {
VariableKinds example = new VariableKinds();
example.showValues(200);
}
}Variable scope and lifetime
Scope determines where a name can be referenced. Lifetime describes how long its storage remains available.
- A block-local variable is visible from its declaration to the end of the enclosing block.
- A method parameter is visible throughout the method body.
- An instance field is available through an object while that object remains reachable.
- A static field is associated with the loaded class.
Default values of fields
Instance and static fields receive default values when an object or class is initialized. Local variables do not receive usable default values and must be definitely assigned before reading.
| Type | Default field value |
|---|---|
byte short int long | 0 or equivalent zero value |
float double | 0.0 or equivalent zero value |
char | '\u0000' |
boolean | false |
| Reference type | null |
Local-variable rule
The compiler prevents reading a local variable that might not have been initialized. This is a compile-time definite-assignment check.
Final variables
A variable declared with final can be assigned only once. For a reference variable, final prevents reassignment of the reference; it does not automatically make the referenced object immutable.
final int MAX_ATTEMPTS = 3;
// MAX_ATTEMPTS = 4; // compile-time errorVariable naming rules and conventions
- An identifier may contain letters, digits, the underscore, and the dollar sign, subject to Java's Unicode identifier rules.
- An identifier cannot begin with a digit.
- A reserved keyword cannot be a variable name.
- Variable names normally use lower camel case, such as
studentCount. - Constants are commonly written in uppercase with underscores, such as
MAX_ATTEMPTS. - Choose descriptive names instead of single letters except for small, conventional contexts.
Complete variable example
public class Student {
static String schoolName = "Prowess Academy"; // static variable
String studentName; // instance variable
int score; // instance variable
Student(String studentName, int score) { // parameters
this.studentName = studentName;
this.score = score;
}
void printReport() {
String result = score >= 50 ? "Pass" : "Try again"; // local variable
System.out.println(studentName + " - " + result);
System.out.println(schoolName);
}
public static void main(String[] args) {
Student student = new Student("Aman", 82); // local variable
student.printReport();
}
}Output
Aman - Pass
Prowess Academy
Common mistakes with Java variables
- Reading a local variable before assigning a value.
- Using a reserved keyword as the variable name.
- Confusing an instance field with a static field.
- Accessing a local variable outside its block.
- Assuming
finalmakes an object immutable. - Using unclear names that hide the purpose of stored values.
int count;
System.out.println(count);int count = 0;
System.out.println(count);What’s next?
Continue with Java Data Types to learn which values each variable type can store.
Lesson summary
- A variable combines a type, an identifier, and stored value.
- Local variables require definite assignment before reading.
- Each object has its own instance fields.
- Static fields belong to the class and are shared.
- Fields receive default values; local variables do not.
finalprevents a variable from being assigned again.
Frequently asked questions
What is a variable in Java?
A variable is a named memory location used to store data values.
What are the types of variables in Java?
Java has three types of variables: instance variables, static variables, and local variables.
Do variables need initialization in Java?
Local variables must be initialized before use, while instance and static variables have default values if not initialized.
Do local variables have default values?
No. Java requires a local variable to be definitely assigned before its value is read. Instance and static fields receive default values.
What is the difference between an instance variable and a static variable?
An instance variable belongs to an object, so each object has its own copy. A static variable belongs to the class and is shared by its instances.
What does final mean for a Java variable?
A final variable can be assigned only once. If it stores an object reference, the reference cannot be reassigned, but the referenced object is not automatically immutable.
What is variable scope in Java?
Scope is the region of source code where a variable name can be referenced. A local variable is limited to its enclosing block, while fields are accessed through their class or object according to access rules.
Check your knowledge
Free learner features
Save your learning progress
Sign in to mark lessons as completed, save your Java learning progress across devices, and participate in lesson discussions.
Sign in to track progressDiscussion
Ask questions, share suggestions, or discuss this lesson.
No approved comments yet. Start the discussion by asking a helpful question.