← Back to libraryQuestion 5 of 273
JavaBeginner

Variables: Scope and Lifecycle

📖 Detailed Explanation:

Java variables are categorized by scope: Local variables (within a method, stored on stack), Instance variables (within a class, stored on heap), and Static variables (shared across all instances, stored in method area). Understanding scope prevents accidental variable shadowing and helps avoid naming conflicts.

🌍 Real-World Example:

Local Variable: Your phone number (only you use it in the function). Instance Variable: Your personal ID (everyone in the class knows it's yours). Static Variable: The country code (everyone in the same country shares it).

🎯 Scenario-Based Interview Question:

What happens if you try to use a local variable without initializing it, versus an instance variable?