What is the use of the static keyword in Java
๐ก Concept: Static Keyword in Java
The static keyword is used to create class-level variables and methods that belong to the class rather than instances.
๐ Quick Intro
Static members are shared across all instances of a class and can be accessed without creating an object.
๐ง Analogy
Think of static members as shared tools in a workshop: everyone uses the same hammer instead of having individual ones.
๐ง Technical Explanation
- Static variables: Shared among all instances.
- Static methods: Can be called without an object.
- Static blocks: Used for static initialization.
- Static nested classes: Nested classes declared static.
- Useful for utility or helper methods and constants.
๐ฏ Use Cases
- โ Define constants with static final.
- โ Utility methods like Math.sqrt() are static.
- โ Maintain counters shared across instances.
๐ป Java Static Keyword Example
class Counter {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
Counter.displayCount(); // Count: 2
}
}

โ Interview Q&A
Q1: What does static mean in Java?
A: Belongs to class, not instance.
Q2: Can static methods access instance variables?
A: No.
Q3: When are static blocks executed?
A: When class loads.
Q4: Can static methods be overridden?
A: No, they are hidden.
Q5: What is a static nested class?
A: Nested class declared static.
Q6: Are static variables thread-safe?
A: No, need synchronization.
Q7: Can you access static members without object?
A: Yes.
Q8: Can static variables be final?
A: Yes, constants.
Q9: Difference between static and instance variables?
A: Static shared; instance per object.
Q10: Use of static keyword?
A: Class-level shared members.
๐ MCQs
Q1. What does static mean in Java?
- Belongs to instance
- Belongs to class, not instance
- Both
- None
Q2. Can static methods access instance variables?
- Yes
- No
- Sometimes
- Depends
Q3. When are static blocks executed?
- At runtime
- When class loads
- When object created
- Never
Q4. Can static methods be overridden?
- Yes
- No
- Sometimes
- Depends
Q5. What is a static nested class?
- Inner class
- Nested class declared static
- Anonymous class
- None
Q6. Are static variables thread-safe?
- Yes
- No
- Sometimes
- Always
Q7. Can you access static members without object?
- No
- Yes
- Sometimes
- Depends
Q8. Can static variables be final?
- No
- Yes
- Sometimes
- Depends
Q9. Difference between static and instance variables?
- Same
- Static shared; instance per object
- Instance shared
- None
Q10. Use of static keyword?
- Instance members
- Class-level shared members
- Local variables
- None
๐ก Bonus Insight
Static keyword enables shared resources and utility methods without creating objects, important for memory efficiency and design.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!