Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 109

Uninitialized Local Variables

Оглавление

Local variables do not have a default value and must be initialized before use. Furthermore, the compiler will report an error if you try to read an uninitialized value. For example, the following code generates a compiler error:

4: public int notValid() { 5: int y = 10; 6: int x; 7: int reply = x + y; // DOES NOT COMPILE 8: return reply; 9: }

The y variable is initialized to 10. By contrast, x is not initialized before it is used in the expression on line 7, and the compiler generates an error. The compiler is smart enough to recognize variables that have been initialized after their declaration but before they are used. Here's an example:

public int valid() { int y = 10; int x; // x is declared here x = 3; // x is initialized here int z; // z is declared here but never initialized or used int reply = x + y; return reply; }

In this example, x is declared, initialized, and used in separate lines. Also, z is declared but never used, so it is not required to be initialized.

The compiler is also smart enough to recognize initializations that are more complex. In this example, there are two branches of code:

public void findAnswer(boolean check) { int answer; int otherAnswer; int onlyOneBranch; if (check) { onlyOneBranch = 1; answer = 1; } else { answer = 2; } System.out.println(answer); System.out.println(onlyOneBranch); // DOES NOT COMPILE }

The answer variable is initialized in both branches of the if statement, so the compiler is perfectly happy. It knows that regardless of whether check is true or false, the value answer will be set to something before it is used. The otherAnswer variable is not initialized but never used, and the compiler is equally as happy. Remember, the compiler is only concerned if you try to use uninitialized local variables; it doesn't mind the ones you never use.

The onlyOneBranch variable is initialized only if check happens to be true. The compiler knows there is the possibility for check to be false, resulting in uninitialized code, and gives a compiler error. You learn more about the if statement in Chapter 3, “Making Decisions.”

On the exam, be wary of any local variable that is declared but not initialized in a single line. This is a common place on the exam that could result in a “Does not compile” answer. Be sure to check to make sure it's initialized before it's used on the exam.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх