Variables in Java
A variable is a container or memory location used to store a value (literal) that can be used later in the program. Variables are essential for holding data temporarily or permanently during program execution.
Classification Based on Scope (Declaration)

Variables in Java are classified based on where they are declared, which determines their scope and lifetime.
Global Variables
- A variable declared inside a class block (but outside any method or block) is known as a global variable.
- Global variables are further classified into:
- Static variables: Declared with the static keyword.
- Non-static variables: Declared without the static keyword.
- Scope: Throughout the class block.
- Default Values: Assigned default values at the time of class loading:
- Integer types (byte, short, int, long): 0
- Decimal types (float, double): 0.0
- boolean: false
- char: '\u0000' (null character)
- Non-primitive types: null
- Access: Can be accessed without initialization due to default values.
- Re-initialization: Cannot be re-declared inside the class block (causes a compile-time error), but can be re-assigned new values.
Static Variables
-
Declared inside the class block with the static keyword.
-
Shared across all instances of the class.
-
Example:
class Example {
static int staticVar = 10; // Static variable
}
Non-Static Variables
- Declared inside the class block without the static keyword.