Programming Java: Observing Scope within a Block

Java developers often experience problems figuring out why an application is misbehaving when encountering a block access problem. The basic guideline is that any variable you create within a block is defined only within that block. For example, when you look at the following code, you see a typical block access scenario.

// Create a variable inside a block.
for (int i = 0; i < 10; i++)
   
   // Display the value of that variable.
   System.out.println("The value of i is: " + i);
// Access outside the block doesn't work.
System.out.println("The value of i is: " + i);

The example displays the value of i within the for loop (a type of block) without problem. However, trying to access i outside the block isn’t acceptable because the variable isn’t defined. The compiler will catch this error.

Another potential problem occurs when a variable is defined in the application and also within a block. Because this situation is likely to create problems, newer versions of Java won’t allow the sort of code shown here:

public static void main(String[] args)
{
   // Define a variable.
   int i = 0;
   
   // Create a variable inside a block.
   for (int i = 0; i < 10; i++)
      
      // Display the value of that variable.
      System.out.println("The value of i is: " + i);
   
   // Access outside the block doesn't work.
   System.out.println("The value of i is: " + i);
}

The compiler won’t always prevent you from shooting yourself in the foot. In many situations, the developer does something with the variable and doesn’t understand the consequences. For example, the following code is perfectly legal in Java.

public static void main(String[] args)
{
   // Define a variable.
   int i = 0;
   
   // Create a variable inside a block.
   for (i = 0; i < 10; i++)
      
      // Display the value of that variable.
      System.out.println("The value of i is: " + i);
   
   // Access outside the block doesn't work.
   System.out.println("The value of i is: " + i);
}

The for loop displays the values 0 through 9 because of the condition within the for loop declaration. The final call to System.out.println() displays a value of 10, not 0 or 9 as some developers might expect.

The i++ part of the declaration occurs, and then the condition is evaluated, so the final value of i is 10, not 9 because it has to be 10 in order for the condition to become false.

The point is that you must consider how a block works with a variable in order to determine whether you can access the variable and what the value will contain on exit from the block.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.