![]() |
VOOZH | about |
Variables in Java are used to store data values during program execution. Each variable is associated with a specific data type that defines the kind of value it can hold. Variables help in performing operations, storing user input, and managing data in a program.
Java variables are divided into different types based on where they are declared and how they are used in a program.
A variable defined within a block, method, or constructor is referred to as a local variable.
Example: Java Program to show the use of local variables
Local Variable: 10
Example: This example demonstrates that local variables are only accessible within the block in which they are declared
x = 10 message = Hello, world! x is greater than 5 Iteration 0 Iteration 1 Iteration 2
Instance variables are known as non-static variables and are declared in a class outside of any method, constructor, or block. Instance variables are created when an object is instantiated and destroyed when the object is destroyed.
Example: This example demonstrates the use of instance variables, which are declared within a class and initialized via a constructor, with default values for uninitialized primitive types.
Geek name is: Sweta Dash Default value for int is 0 Default value for Integer is: null
Static variables in Java are variables declared with the static keyword inside a class but outside any method. They are shared among all objects of the class and exist for the entire lifetime of the program.
Example: This example demonstrates the use of static variables, which belong to the class and can be accessed without creating an object of the class.
Geek Name is: Sweta Dash
| Feature | Local Variable | Instance Variable | Static Variable |
|---|---|---|---|
| Declared | Inside method/block | Inside class, outside methods | Inside class with static keyword |
| Scope | Only within the block/method | Across class methods (non-static) | Shared across all objects of class |
| Lifetime | Exists only during method/block | Exists as long as object exists | Exists throughout program execution |
| Number of Copies | Each method call creates new | Each object has its own copy | Only one copy for the class |
| Default Value | No default; must initialize | Default based on type (0, null) | Default based on type (0, null) |
| Access | Only within method/block | Through objects | Through class name (or object) |
| Initialization | Required before use | Optional; can use constructors | Optional; can use static blocks |