Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Java - Static Keyword
Consider this code:
class Config {
  static String env;
  static {
    env = System.getenv("APP_ENV");
    if (env == null) env = "dev";
  }
}

What is the purpose of the static block here?
ATo delay environment variable reading until object creation
BTo set a default environment if none is provided externally
CTo allow multiple environment variables to be set later
DTo prevent environment variable from being changed
Step-by-Step Solution
Solution:
  1. Step 1: Analyze static block logic

    The block reads an environment variable and assigns a default if null.
  2. Step 2: Understand static block timing

    This runs once at class load, ensuring env is set before use.
  3. Final Answer:

    To set a default environment if none is provided externally -> Option B
  4. Quick Check:

    Static block sets default static variable values [OK]
Quick Trick: Use static blocks to set defaults for static variables [OK]
Common Mistakes:
  • Thinking static block runs on object creation
  • Assuming environment variable can be changed later
  • Confusing static block with instance initializer

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes