Apr 5, 2012

Various Variable Scopes,Class Method and Block scopes

Broadly speaking, there are three level of scopes in which the variables defined in Java come and these are:

1) Class level variables : The member variables present inside the class are known as class level variables. These variables could be accessible outside the class if the access specifier is public.

These variables take default value if not provided explicitly.

public class MyTest {
static int a = 10;
public static void main(String[] args) {
System.out.println(a);
}

}


2) Method level variables : Method level variables are defined inside the methods. These variables don't have any default values assigned to them and a compiler error is generated when a method level variables is used without assigning a value to it explicitly.

public class MyTest {

public static void main(String[] args) {
int a = 10;
System.out.println(a);
}

}


3) Block level variables : The block can be a normal block or static block. If using the static block then the variable should have static modifier.

public class MyTest {
static {
int a = 10;
}

public static void main(String[] args) {
System.out.println(a);
}
}

No comments:

Post a Comment