Explain the concept of variables in Java. What are the types of variables?
In Java, a variable is a container for storing data values during the execution of a program. Variables are associated with a specific data type, which determines the kind of values they can hold (e.g., integers, characters, etc.). Each variable must have a name and type. Variables act as named memory locations that allow programs to manipulate data.
Types of Variables in Java
Java has three main types of variables:
Local Variables
Defined within a method, constructor, or block.
Only accessible within the scope where they are declared.
Must be initialized before use.
Example:
void show() {
int num = 5; // local variable
System.out.println(num);
}
Instance Variables
Declared inside a class but outside methods or constructors.
Belong to an instance of the class (each object has its own copy).
Default values are assigned if not explicitly initialized (e.g., 0 for int, null for objects).
Example:
class Person {
String name; // instance variable
int age; // instance variable
}
Static Variables
Declared with the static keyword inside a class.
Shared among all objects of the class (single copy).
Useful for constants or data shared across instances.
Example:
class Example {
static int count = 0; // static variable
}