Methods and Scoping

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > User-Defined_Methods

Introduction

Just like loop scope, user-defined method definitions have their own scope. Variables declared in a method body may only be accessed within that same method body.

The scope of a variable is the section of a program where a variable can be accessed.

A block is a section of code that is between an opening and closing brace. Variables that are defined inside a block section, called local variables, have block scope. Local variables declared within a block scope may only be used within the same block.


public class MyClass 
{

	public static void main(String[] args)
	{
		int first = 23;
		int second = 68;
		int great;
                System.out.println(biggest);             // this is invalid

		great = getGreaterInt(first, second);
 
                System.out.println(great);               // this is vaild

	}
   
  
        public static int getGreaterInt( int value1, int value2 )	// start of block 1
	{								// block 1
		int biggest; 						// block 1
									// block 1
		if ( value1 > value ) 					// block 1
		{							// block 1
			biggest = value1;				// block 1
		}							// block 1	
		else							// block 1
		{							// block 1
			biggest = value2;				// block 1
		}					                // block 1
                                                                        // block 1
		great = biggest;	// this is invalid	        // block 1									                                // block 1
                                                                        // block 1
		return biggest;						// block 1
        }						  	        // end of block 1 
 
} // end of MyClass

The above code is a class called MyClass.

My class contains two methods, the main method and a user-defined method, getGreaterInt.


The section in blue has block scope. The int 'biggest' can only be read within block 1. Note that the int biggest is a local variable to the method named: getGreaterInt.

If the main method tried to access biggest, a compile-time error would occur. The main method cannot access the int biggest because biggest is outside of block 1 scope.

Also note that the int 'great' can not be accessed from the getGreaterInt method. The variable 'great' is initialized in the main method and can not be accessed from the getGreaterInt method.


In short: A variable declared in a method can only be used in that method.