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

Tracing Scope

Оглавление

The exam will attempt to trick you with various questions on scope. You'll probably see a question that appears to be about something complex and fails to compile because one of the variables is out of scope.

Let's try one. Don't worry if you aren't familiar with if statements or while loops yet. It doesn't matter what the code does since we are talking about scope. See if you can figure out on which line each of the five local variables goes into and out of scope:

11: public void eatMore(boolean hungry, int amountOfFood) { 12: int roomInBelly = 5; 13: if (hungry) { 14: var timeToEat = true; 15: while (amountOfFood> 0) { 16: int amountEaten = 2; 17: roomInBelly = roomInBelly - amountEaten; 18: amountOfFood = amountOfFood - amountEaten; 19: } 20: } 21: System.out.println(amountOfFood); 22: }

This method does compile. The first step in figuring out the scope is to identify the blocks of code. In this case, there are three blocks. You can tell this because there are three sets of braces. Starting from the innermost set, we can see where the while loop's block starts and ends. Repeat this process as we go on for the if statement block and method block. Table 1.10 shows the line numbers that each block starts and ends on.

TABLE 1.10 Tracking scope by block

Line First line in block Last line in block
while 15 19
if 13 20
Method 11 22

Now that we know where the blocks are, we can look at the scope of each variable. hungry and amountOfFood are method parameters, so they are available for the entire method. This means their scope is lines 11 to 22. The variable roomInBelly goes into scope on line 12 because that is where it is declared. It stays in scope for the rest of the method and goes out of scope on line 22. The variable timeToEat goes into scope on line 14 where it is declared. It goes out of scope on line 20 where the if block ends. Finally, the variable amountEaten goes into scope on line 16 where it is declared. It goes out of scope on line 19 where the while block ends.

You'll want to practice this skill a lot! Identifying blocks and variable scope needs to be second nature for the exam. The good news is that there are lots of code examples to practice on. You can look at any code example on any topic in this book and match up braces.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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