T19: Knowledge Tip Of The Day....
Scope of Variables In Java
* Member Variables (Class Level
Scope)
These variables must be declared
inside class (outside any function). They can be directly accessed anywhere in
class.
- We can declare class variables
anywhere in class, but outside methods.
- Access specified of member variables doesn’t effect scope of them within a class.
- Member variables can be accessed outside a class with following rules
- Access specified of member variables doesn’t effect scope of them within a class.
- Member variables can be accessed outside a class with following rules
* Local Variables (Method Level
Scope)
Variables declared inside a
method have method level scope and can’t be accessed outside the method.
Note :: Local variables don’t
exist after method’s execution is over.
* Loop Variables (Block Scope)
A variable declared inside pair
of brackets “{” and “}” in a method has scope withing the brackets only.
e.g. for (int x = 0; x < 4; x++)
{
System.out.println(x);
}
System.out.println(x); // Will produce error
e.g. for (int x = 0; x < 4; x++)
{
System.out.println(x);
}
System.out.println(x); // Will produce error
Some Important Points about
Variable scope in Java:
- In general, a set of curly
brackets { } defines a scope.
- In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined.
- Any variable defined in a class outside of any method can be used by all member methods.
- When a method has same local variable as a member, this keyword can be used to reference the current class variable.
- For a variable to be read after the termination of a loop, It must be declared before the body of the loop.
- In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined.
- Any variable defined in a class outside of any method can be used by all member methods.
- When a method has same local variable as a member, this keyword can be used to reference the current class variable.
- For a variable to be read after the termination of a loop, It must be declared before the body of the loop.
No comments:
Post a Comment