Method and class variables

A variable can be created either at class level or method level. A class level variable is also known as a field and is visible from within any method in that class. By contrast a method level variable is only visible within that method. Method level variables are sometimes called local variables, as their scope is local to the method. Another important property of a method level variable is that it comes into existence when the code enters the class and does not persist between calls to the class. Thus if you take the example of the following code.

Void amethod(){
int i = 1;
}

The variable i will be re-initialised each time amethod is called.

Method variables are not given default values and if you attempt to use them without assigning a value it will generate a compile time error. The following code demonstrates this.

public class MetVar{
	public static void main(String argv[]){
		MetVar mv = new MetVar();
		mv.amethod();
		}
		public void amethod(){
		int i;
		System.out.println(i);
		}
}

If you attempt to compile this code it will generate the error

MetVar.java:8: variable i might not have been initialized
                System.out.println(i);
                                   ^
1 error
Last modified: Sunday, 20 September 2015, 07:21 PM