3.1. Scope of variables

[1.1] Define the scope of variables

The scope of a variable specifies its life span and its visibility. In this section, we’ll cover the scopes of variables, including the domains in which they’re accessible. Here are the available scopes of variables:

  • Local variables (also known as method-local variables)
  • Method parameters (also known as method arguments)
  • Instance variables (also known as attributes, fields, and nonstatic variables)
  • Class variables (also known as static variables)

As a rule of a thumb, the scope of a variable ends when the brackets of the block of code it’s defined in get closed. This might be hard to understand now, but it will become clearer when you go through the examples. Let’s get started by defining local variables.

3.1.1. Local variables

Local variables are defined within a method. They may or may not be defined within code constructs such as if-else constructs, looping constructs, or switch statements. Typically, you’d use local variables to store the intermediate results of a calculation. Compared to the other three variable scopes listed previously, they have the shortest scope (life span).

In the following code, a local variable avg is defined within the method get-Average():

As you can see, the variable avg, defined locally in the method getAverage, can’t be accessed outside it, in the method setAverage. The scope of this local variable, avg, is depicted in figure 3.1. The unshaded area marks where avg is accessible, and the shaded area is where it won’t be available.

Note

The life span of a variable is determined by its scope. If the scope of a variable is limited to a method, its life span is also limited to that method. You may notice that these terms are used interchangeably.

Figure 3.1. You can access the local variable avg only within the method getAverage.

Let’s define another variable, avg, local to the if block of an if statement (code that executes when the if condition evaluates to true):

In this case, the scope of the local variable avg is reduced to the if block of the if-else statement defined within the getAverage method. The scope of this local variable avg is depicted in figure 3.2, where the unshaded area marks where avg is accessible, and the shaded part marks the area where it won’t be available.

Figure 3.2. The scope of local variable avg is part of the if statement.

Similarly, loop variables aren’t accessible outside the loop body:

Exam Tip

The local variables topic is a favorite of OCA Java SE 8 Programmer I exam authors. You’re likely to be asked a question that seems to be about a rather complex topic, such as inheritance or exception handling, but instead it’ll be testing your knowledge on the scope of a local variable.

Can a local variable be accessed in a method, before its declaration? No. A forward reference to local variables isn’t allowed:

If you reverse the declaration of the variables in the preceding example, the code will compile:

The scope of a local variable depends on the location of its declaration within a method. The scope of local variables defined within a loop, if-else, or switch construct or within a code block (marked with {}) is limited to these constructs. Local variables defined outside any of these constructs are accessible across the complete method.

The next section discusses the scope of method parameters.

3.1.2. Method parameters

The variables that accept values in a method signature are called method parameters. They’re accessible only in the method that defines them. In the following example, a method parameter val is defined for the method setTested:

In the preceding code, you can access the method parameter val only within the method setTested. It can’t be accessed in any other method.

The scope of the method parameter val is depicted in figure 3.3. The unshaded area marks where the variable is accessible, and the shaded part marks where it won’t be available.

Figure 3.3. The scope of the method parameter val, which is defined in the method setTested

The scope of a method parameter may be as long as that of a local variable or longer, but it can never be shorter. The following method, isPrime, defines a method parameter, num, and two local variables, result and ctr:

The scope of the method parameter num is as long as the scope of the local variable result. Because the scope of the local variable ctr is limited to the for block, it’s shorter than the method parameter num. The comparison of the scope of all of these three variables is shown in figure 3.4, where the scope of each variable (defined in an oval) is shown by the rectangle enclosing it.

Figure 3.4. Comparison of the scope of method parameters and local variables

Let’s move on to instance variables, which have a larger scope than method parameters.

3.1.3. Instance variables

Instance is another name for an object. Hence, an instance variable is available for the life of an object. An instance variable is declared within a class, outside all the methods. It’s accessible to all the instance (or nonstatic) methods defined in a class.

In the following example, the variable tested is an instance variable—it’s defined within the class Phone, outside all the methods. It can be accessed by all the methods of class Phone:

The scope of the instance variable tested is depicted in figure 3.5. As you can see, the variable tested is accessible across the object of class Phone, represented by the unshaded area. It’s accessible in the methods setTested and isTested.

Figure 3.5. The instance variable tested is accessible across the object of class Phone.

Exam Tip

The scope of an instance variable is longer than that of a local variable or a method parameter.

Class variables, covered in the next section, have the largest scope of all types of variables.

3.1.4. Class variables

A class variable is defined by using the keyword static. A class variable belongs to a class, not to individual objects of the class. A class variable is shared across all objects—objects don’t have a separate copy of the class variables.

You don’t even need an object to access a class variable. It can be accessed by using the name of the class in which it’s defined:

Let’s try to access this variable in another class:

As you can see in the preceding code, the class variable softKeyboard is accessible using all the following:

  • Phone.softKeyboard
  • p1.softKeyboard
  • p2.softKeyboard

It doesn’t matter whether you use the name of the class (Phone) or reference to an object (p1) to access a class variable. You can change the value of a class variable using either of them because they all refer to a single shared copy. When you access static variable softKeyboard, Java refers to the type of reference variables p1 and p2 (which is Phone) and not to the objects referred to by them. So accessing a static variable using a null reference won’t throw an exception:

The scope of the class variable softKeyboard is depicted in figure 3.6. As you can see, a single copy of this variable is accessible to all the objects of the class Phone. The variable softKeyboard is accessible even without the existence of any Phone instance. The class variable softKeyboard is made accessible by the JVM when it loads the Phone class into memory. The scope of the class variable softKeyboard depends on its access modifier and that of the Phone class. Because the class Phone and the class variable softKeyboard are defined using default access, they’re accessible only within the package com.mobile.

Figure 3.6. The scope of the class variable softKeyboard is limited to the package com.mobile because it’s defined in the class Phone, which is defined with default access. The class variable softKeyboard is shared and accessible across all objects of the class Phone.

Comparing the use of variables in different scopes

Here’s a quick comparison of the use of the local variables, method parameters, instance variables, and class variables:

  • Local variables are defined within a method and are normally used to store the intermediate results of a calculation.
  • Method parameters are used to pass values to a method. These values can be manipulated and may also be assigned to instance variables.
  • Instance variables are used to store the state of an object. These are the values that need to be accessed by multiple methods.
  • Class variables are used to store values that should be shared by all the objects of a class.

3.1.5. Overlapping variable scopes

In the previous sections on local variables, method parameters, instance variables, and class variables, did you notice that some of the variables are accessible in multiple places within an object? For example, all four variables will be accessible in a loop within a method.

This overlapping scope is shown in figure 3.7. The variables are defined in ovals and are accessible within all methods and blocks, as illustrated by their enclosing rectangles.

Figure 3.7. The scopes of variables can overlap.

As shown in figure 3.7, an individual copy of classVariable can be accessed and shared by multiple objects (object1 and object2) of a class. Both object1 and object2 have their own copy of the instance variable instanceVariable, so instance-Variable is accessible across all the methods of object1. The methods method1 and method2 have their own copies of localVariable and methodParameter when used with object1 and object2.

Note

The scope of instanceVariable overlaps with the scope of local-Variable and methodParameter, defined in method1. Hence, all three of these variables (instanceVariable, localVariable, and methodParameter) can access each other in this overlapped area. But instanceVariable can’t access localVariable and methodParameter outside method1.

Comparing the scope of variables

Figure 3.8 compares the life spans of local variables, method parameters, instance variables, and class variables.

Figure 3.8. Comparing the scope, or life span, of all four variables

As you can see in figure 3.8, local variables have the shortest scope or life span, and class variables have the longest scope or life span.

Exam Tip

Different local variables can have different scopes. The scope of local variables may be shorter than or as long as the scope of method parameters. The scope of local variables is less than the scope of a method if they’re declared in a sub-block (within braces {}) in a method. This sub-block can be an if statement, a switch construct, a loop, or a try-catch block (discussed in chapter 7).

Variables with the same name in different scopes

The fact that the scopes of variables overlap results in interesting combinations of variables within different scopes but with the same names. Some rules are necessary to prevent conflicts. In particular, you can’t define a static variable and an instance variable with the same name in a class:

Similarly, local variables and method parameters can’t be defined with the same name. The following code defines a method parameter and a local variable with the same name, so it won’t compile:

A class can define local variables with the same name as the instance or class variables, also referred to as shadowing. The following code defines a class variable and a local variable, softKeyboard, with the same name, and an instance variable and a local variable, phoneNumber, with the same name, which is acceptable:

Note

Defining variables with the same name in overlapping scopes can be a dangerous coding practice. It’s usually accepted only in very specific situations, like constructors and setters. Please write code that’s easy to read, comprehend, and maintain.

What happens when you assign a value to a local variable that has the same name as an instance variable? Does the instance variable reflect this modified value? This question provides the food for thought in this chapter’s first Twist in the Tale exercise. It should help you remember what happens when you assign a value to a local variable when an instance variable already exists with the same name in the class (answer in the appendix).

Twist in the Tale 3.1

The class Phone defines a local variable and an instance variable, phoneNumber, with the same name. Examine the definition of the method setNumber. Execute the class on your system and select the correct output of the class TestPhone from the given options:

class Phone {
    String phoneNumber = "123456789";
    void setNumber () {
        String phoneNumber;
        phoneNumber = "987654321";
    }
}
class TestPhone {
    public static void main(String[] args) {
        Phone p1 = new Phone();
        p1.setNumber();
        System.out.println (p1.phoneNumber);
    }
}

  1. 123456789
  2. 987654321
  3. No output
  4. The class Phone will not compile.

In this section, you worked with variables in different scopes. When variables go out of scope, they’re no longer accessible by the remaining code. In the next section, you’ll see how an object is created and made accessible and then inaccessible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59