Scope of Variables In Java
Categories: Java 8(JDK1.8)
Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories.
Member Variables (Class Level Scope)
These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example:
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}
1. We can declare class variables anywhere in class, but outside methods.
2. Access specified of member variables doesn’t affect scope of them within a class.
3. Member variables can be accessed outside a class with following rules