Java Interview Questions
Java Static Variables, Methods, and Classes - Theory Questions
1. What is the static keyword in Java and what does it signify?
The static keyword in Java indicates that a member (variable, method, or class) belongs to the class itself rather than to instances of the class. Key characteristics:
- Shared across all instances of the class
- Can be accessed without creating an object
- Loaded when the class is first loaded by JVM
- Associated with the class, not with objects
- Can be used with variables, methods, blocks, and nested classes
2. What are static variables and how do they differ from instance variables?
Static Variables:
- One copy per class, shared by all instances
- Memory allocated once when class is loaded
- Accessed using class name: ClassName.variableName
- Also called class variables
Instance Variables:
- Separate copy for each object instance
- Memory allocated when object is created
- Accessed using object reference: object.variableName
- Also called non-static variables
3. What are static methods and what are their limitations?
Static Methods:
- Belong to the class, not to any instance
- Can be called without creating an object
- Accessed using class name: ClassName.methodName()
Limitations:
- Cannot access instance variables directly
- Cannot call non-static methods directly
- Cannot use this or super keywords
- Cannot be overridden (but can be hidden)
4. What is the difference between static and non-static methods?
Static Methods:
- Called using class name
- Can only access static members directly
- Cannot be overridden
- No this reference available
- Loaded when class is loaded
Non-static Methods:
- Called using object reference
- Can access both static and non-static members
- Can be overridden
- Have this reference to current object
- Loaded when object is created
5. What are static blocks and when are they executed?
Static blocks are used for static initialization:
class Example {
static {
// static initialization code
System.out.println("Static block executed");
}
}
Characteristics:
- Executed when class is first loaded by JVM
- Executed only once, before constructor
- Used to initialize static variables
- Can have multiple static blocks (executed in order)
- Cannot throw checked exceptions
6. What are static nested classes and how do they differ from inner classes?
Static Nested Class:
- Declared with static keyword inside another class
- Can be instantiated without outer class instance
- Can only access static members of outer class
- Example: OuterClass.StaticNestedClass obj = new OuterClass.StaticNestedClass();
Inner Class (non-static):
- Requires outer class instance to be created
- Can access both static and non-static members of outer class
- Has implicit reference to outer class instance
7. Can we override static methods in Java?
No, static methods cannot be overridden. However, they can be hidden:
class Parent {
static void display() { System.out.println("Parent"); }
}
class Child extends Parent {
static void display() { System.out.println("Child"); } // method hiding
}
In method hiding:
- Which method is called depends on reference type, not object type
- No runtime polymorphism for static methods
- Use @Override annotation causes compile error
8. What is the order of execution of static blocks, instance blocks, and constructors?
Execution order when creating an object:
1. Static blocks of parent class (when class loaded)
2. Static blocks of child class (when class loaded)
3. Instance initialization blocks of parent class
4. Constructor of parent class
5. Instance initialization blocks of child class
6. Constructor of child class
Static blocks execute only once when class is first referenced.
9. Can static methods be abstract?
No, static methods cannot be abstract because:
- Abstract methods require implementation in subclass
- Static methods belong to the class and cannot be overridden
- Static methods are resolved at compile-time, while abstract methods need runtime resolution
- Combination of static and abstract is contradictory and not allowed
Example: abstract static void method(); // Compile error
10. Can we use "this" and "super" in static context?
No, both this and super cannot be used in static context because:
- this refers to current object instance, but static methods don't have object context
- super refers to parent class instance, which also requires object context
- Static methods are class-level, while this and super are instance-level
Using them in static methods results in compile-time error.
11. What are the common use cases for static variables?
Common use cases for static variables:
- Constants: public static final double PI = 3.14159;
- Counters: Track number of objects created
- Shared resources: Database connections, configuration
- Cache: Shared cache across instances
- Utility values: Application-wide settings
Example:
class Car {
static int carCount = 0; // shared counter
public Car() { carCount++; }
}
12. What are the common use cases for static methods?
Common use cases for static methods:
- Utility methods: Math.sqrt(), Arrays.sort()
- Factory methods: Create objects without exposing creation logic
- Singleton pattern: Get instance method
- Input validation: Validation methods that don't need object state
- Main method: Entry point of application
Example:
class StringUtils {
public static boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
13. Can a class be declared as static?
Top-level classes cannot be declared as static. Only nested classes can be static:
class Outer {
static class Nested { // valid
// static nested class
}
}
static class TopLevel { // invalid - compile error
}
Static nested classes are essentially top-level classes nested within another class for packaging convenience.
14. What is the memory allocation for static members?
Memory allocation for static members:
- Static variables: Stored in Method Area (part of JVM memory)
- Static methods: Code stored in Method Area
- Allocation time: When class is loaded by ClassLoader
- Deallocation time: When class is unloaded (rare in practice)
- Lifetime: Entire duration of application (usually)
This differs from instance members which are allocated in Heap when objects are created.
15. Can we access static members from non-static context?
Yes, static members can be accessed from non-static context:
- From instance methods
- From constructors
- From instance initialization blocks
Example:
class Example {
static int count = 0;
void instanceMethod() {
count++; // accessing static variable from instance method
staticMethod(); // calling static method from instance method
}
static void staticMethod() { ... }
}
However, the reverse is not true.
16. What are the thread safety concerns with static variables?
Static variables pose thread safety concerns because:
- They are shared across all threads in the application
- Concurrent modifications can lead to race conditions
- Need synchronization for mutable static variables
Solutions:
- Use synchronized methods/blocks
- Use volatile keyword for visibility
- Use atomic classes from java.util.concurrent.atomic
- Prefer immutable static objects
- Use ThreadLocal for thread-specific data
17. Can static methods be synchronized?
Yes, static methods can be synchronized:
class Counter {
static int count = 0;
public static synchronized void increment() {
count++;
}
}
When a static method is synchronized:
- It acquires the lock on the class object (ClassName.class)
- Different from instance synchronized methods which lock on object instance
- Only one thread can execute any synchronized static method of the class at a time
18. What is the difference between static import and regular import?
Regular Import:
- Imports classes and interfaces
- Example: import java.util.List;
- Allows using class name without package prefix
Static Import:
- Imports static members (variables and methods)
- Example: import static java.lang.Math.PI;
- Allows using static members without class name prefix
- Use sparingly to avoid confusion
- Example usage: double area = PI * radius * radius;
19. Can we have static constructors in Java?
No, Java does not have static constructors. However, static initialization blocks serve similar purposes:
class Database {
static Connection connection;
static {
// static initialization - similar to static constructor
connection = DriverManager.getConnection(...);
}
}
Static blocks are executed when class is loaded and can initialize static variables.
20. What are the best practices for using static in Java?
Best practices:
- Use static for constants and utility methods
- Avoid mutable static variables (thread safety issues)
- Prefer dependency injection over static utility classes
- Use static final for true constants
- Consider making utility class constructors private
- Use static imports judiciously
- Document thread safety of static methods
- Avoid static for state that should be instance-specific
- Use static nested classes when no access to instance members needed