Java Variable-interview
Q1. What is a variable in Java?
A variable in Java is a name given to a memory location that stores data during program execution. Its value can change depending on the logic.
Q2. What are the different types of variables in Java?
Java supports three main types of variables:
- Local Variables – Declared inside a method or block, accessible only within it.
- Instance Variables – Declared inside a class but outside any method, each object gets its own copy.
- Static Variables – Declared using the static keyword, shared among all objects of the class.
Q3. What is the default value of variables in Java?
Local variables do not have default values and must be initialized before use. Instance and static variables have default values based on their data type (e.g., 0 for int, null for objects, false for boolean).
Q4. What is the difference between an instance variable and a static variable?
Instance variables belong to objects (each object has its own copy), while static variables belong to the class (shared across all objects).
Q5. Can we declare a variable as both final and static in Java?
Yes. A static final variable is a constant in Java, meaning its value cannot be changed after initialization.