Variable Scope


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 5.  Methods

The Chapter 4, "Flow Control," started discussing scope and scoping rules, but now you have enough knowledge to formalize these concepts.

The scope of an identifier for a variable, reference, or method is the portion of the program in which the identifier can be referenced.

There are three types of scope defined in Java:

  • Class Scope: Available to all methods in the class

  • Block Scope: Available only with the block it is declared to, or within nested blocks

  • Method Scope: Special type for labels used with break and continue statements

Listing 5.3 shows a sample application with variables at differing scopes.

Listing 5.3
 public class Scope {    static int x = 5;    public static int timesX( int n ) {      int result = n*x;      return result;    }    public static void main( String[] args ) {      int m = 10;      System.out.println( "m times x = " + timesX( m ) );    }  } 

In Listing 5.3 there are 3 variables: x, n, and m. Table 5.1 lists the type of scope they have and to which method (if applicable).

Table 5.1. Variable Scoping





Class Scope

The entire Scope class



The timesX method



The main method

x is a variable defined outside of a method and inside the class Scope, so it is said to have class scope, and is therefore visible from all methods in the class. m is defined inside the main method, so it has local or block scope to the main method. n is declared inside the parameter list of the timesX method, so it has local or block scope to the timesX method.

A local variable declared in a block can only be used in that block or nested blocks within that block.


    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: