Java variable types by scope and lifetime
Java variable types are usually classified by where the variable is declared and how long it exists. In Java, the main variable categories are instance variables, static variables, local variables, and method parameters.
A variable is a named storage location that holds a value of a specific data type. The data type tells Java what kind of value the variable can store, while the variable category tells you where the variable can be used and whether it belongs to an object, a class, a method, or a method call.
Java variable declaration syntax
A Java variable declaration normally has a data type followed by a variable name. You can also assign an initial value during declaration.
dataType variableName;
dataType variableName = value;
For example, int count = 10; declares a variable named count that can store an integer value. The same declaration pattern is used for local variables, instance variables, static variables, and parameters, but their placement changes their behavior.
Four types of variables in Java
The following table gives a quick comparison of the four Java variable types covered in this tutorial.
| Java variable type | Where it is declared | Belongs to | Lifetime | Default value |
|---|---|---|---|---|
| Instance variable | Inside a class, outside methods, constructors, and blocks | Each object | As long as the object exists | Yes |
| Static variable | Inside a class with the static keyword | The class | As long as the class is loaded | Yes |
| Local variable | Inside a method, constructor, or block | The block where it is declared | Until the block finishes execution | No |
| Method parameter | Inside the method declaration parentheses | The method call | Until the method finishes execution | Receives value from caller |
Each section below provides detailed descriptions and example programs to help you understand and effectively use each type of variable in Java.
1 Instance Variables
Instance variables are declared inside a class but outside any method, constructor, or block. Each object of the class has its own copy of the instance variable.
An instance variable is useful when each object must maintain its own state. For example, two Car objects can have different speed values because speed belongs to the object, not to the class as a whole.
Example Program:
public class Car {
// Instance variable
int speed = 60;
public void displaySpeed() {
System.out.println("Car Speed: " + speed + " km/h");
}
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
// Changing the instance variable for car2
car2.speed = 80;
car1.displaySpeed(); // Expected output: Car Speed: 60 km/h
car2.displaySpeed(); // Expected output: Car Speed: 80 km/h
}
}
Output:
Car Speed: 60 km/h
Car Speed: 80 km/h
This program uses the Car class to demonstrate instance variables. The speed variable is an instance variable, meaning that each Car object (here, car1 and car2) has its own separate copy. Changing the speed of car2 does not affect the speed of car1, as seen in the output.
Instance variables get default values if you do not initialize them. For example, numeric instance variables default to 0, boolean variables default to false, and object references default to null.
2 Static Variables
Static variables, also known as class variables, are declared with the static keyword inside a class but outside any method, constructor, or block. They are shared among all instances of the class.
A static variable is useful when one common value must be shared by all objects of the class. It is usually accessed using the class name, such as Bicycle.gear, because the variable belongs to the class.
Example Program:
public class Bicycle {
// Static variable
static int gear = 3;
public static void main(String[] args) {
// Accessing the static variable without creating an object
System.out.println("Default Gear: " + gear);
// Creating objects of Bicycle
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Changing the static variable using one object
bike1.gear = 5;
System.out.println("Gear from bike2: " + bike2.gear);
}
}
Output:
Default Gear: 3
Gear from bike2: 5
In this program, the Bicycle class demonstrates the use of a static variable, gear. Since gear is static, it is shared across all instances of Bicycle. When the value of gear is changed through bike1, the change is reflected when accessing it from bike2, as shown in the output.
For readability, prefer accessing static variables through the class name instead of through an object reference. This makes it clear that the value is shared at the class level.
3 Local Variables
Local variables are declared within a method, constructor, or block. They are created when the method is invoked and destroyed once the method finishes execution. Local variables must be explicitly initialized before use.
A local variable is visible only inside the block where it is declared. This makes local variables suitable for temporary values used during a calculation, loop, condition, or method execution.
Example Program:
public class Truck {
public static void main(String[] args) {
// Local variable declaration and initialization
int loadWeight = 1000;
System.out.println("Truck Load Weight: " + loadWeight + " kg");
}
}
Output:
Truck Load Weight: 1000 kg
This Truck class example shows a local variable loadWeight defined within the main method. Since it is local, it is only accessible within the method. The program prints the truck’s load weight, illustrating how local variables function in Java.
Unlike instance and static variables, local variables do not receive default values. If a local variable is declared but not initialized before it is used, the program will not compile.
4 Method Parameters
Method parameters are variables passed to methods. They are used as local variables within the method and hold the values provided during the method call.
Parameters help a method work with different input values without hard-coding those values inside the method body. In the example below, a and b receive the values passed from the main method.
Example Program:
public class Calculator {
// Method with parameters
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(15, 25);
System.out.println("Sum: " + result);
}
}
Output:
Sum: 40
The Calculator class demonstrates the use of method parameters. The add method takes two parameters (a and b), adds them, and returns the result. When called from the main method with the values 15 and 25, the method returns their sum, which is printed to the console.
Java variable types and the 8 primitive data types
Variable type and data type are related, but they are not the same idea. Variable type in this tutorial refers to categories such as instance, static, local, and parameter. Data type refers to the kind of value stored in a variable, such as int, double, or boolean.
Java has eight primitive data types. These are often asked along with Java variable types because every variable must be declared with a data type.
| Primitive data type | Common use | Example value |
|---|---|---|
byte | Small integer values | 100 |
short | Short integer values | 12000 |
int | General integer values | 250 |
long | Large integer values | 9000000000L |
float | Decimal values with single precision | 12.5f |
double | Decimal values with double precision | 45.75 |
char | Single character values | 'A' |
boolean | True or false values | true |
Default values for Java instance and static variables
Instance variables and static variables are initialized with default values when an explicit value is not provided. Local variables are different; they must be initialized before use.
| Data type | Default value for fields |
|---|---|
byte, short, int, long | 0 or equivalent zero value |
float, double | 0.0 or equivalent zero value |
char | Null character |
boolean | false |
| Object reference | null |
Common mistakes with Java variable types
- Using a local variable before assigning a value to it.
- Expecting an instance variable change in one object to update another object automatically.
- Accessing static variables through object names instead of the class name.
- Confusing Java variable categories with Java primitive data types.
- Declaring a variable in a narrow block and trying to access it outside that block.
Java variable types FAQs
What are the four types of variables in Java?
The four types of variables in Java are instance variables, static variables, local variables, and method parameters. Instance variables belong to objects, static variables belong to the class, local variables belong to a method or block, and method parameters receive values from method calls.
What are the 8 data types in Java?
The eight primitive data types in Java are byte, short, int, long, float, double, char, and boolean. These are data types, not variable categories. A variable category tells where the variable is declared, while a data type tells what kind of value it can store.
What is the difference between instance and static variables in Java?
An instance variable has a separate copy for each object of the class. A static variable has one shared copy for the class, so changes to the static variable are visible through all objects of that class.
Why must local variables be initialized in Java?
Local variables do not get default values in Java. Because of this, Java requires a local variable to be assigned a value before it is read or used in an expression.
Are method parameters local variables in Java?
Method parameters behave like local variables inside the method. The difference is that their values come from the method call, while ordinary local variables are declared inside the method body or block.
Java variable types summary for beginners
In this Java Tutorial, we explored the different types of variables in Java. We covered instance variables, static variables, local variables, and method parameters, providing detailed explanations, example programs, and output for each.
To choose the right Java variable type, first decide where the value should live. Use an instance variable when each object needs its own value, a static variable when the class should share one value, a local variable for temporary method-level work, and a method parameter when the value should be supplied by the caller.
Java variable types editorial QA checklist
- Confirm that the tutorial separates Java variable categories from Java data types.
- Check that instance variables are described as object-level variables with separate copies for each object.
- Check that static variables are described as class-level variables shared across all objects.
- Verify that local variables are clearly marked as requiring explicit initialization before use.
- Ensure the FAQ answers the common beginner questions about four Java variable types and eight Java primitive data types.
TutorialKart.com