Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


What happens if a local variable in a method is not initialized?

  1. Compilation error

  2. NullPointerException

  3. It is initialized to a default value.

  4. Runtime error

The correct answer is: Compilation error

When a local variable is declared in a method, it must be initialized with a value before it can be used. If it is not initialized, the compiler will throw an error and the code will not compile. This is because the compiler cannot determine which value to assign to the variable, and therefore cannot continue with the compilation process. Options B, C, and D are incorrect because a null pointer exception or runtime error would only occur during execution of the program, not during compilation. Additionally, local variables do not have default values, only instance variables do.