Intern
What is scope?
sobes.tech AI
Answer from AI
Scope in Java defines the accessibility of variables, methods, and classes in a program. It determines where and from which parts of the code an element can be accessed.
Main scopes:
- Class Scope: Variables and methods declared at the class level are accessible within this class. If they are declared with access modifiers
public,protected, or default (no modifier), their accessibility extends beyond the class itself. - Method Scope: Variables declared inside a method (local variables) are accessible only within that method. They are created when the method is entered and destroyed when it is exited.
- Block Scope: Variables declared inside a code block (e.g., within
for,while,ifstatements, or simply within curly braces{}) are accessible only within that block.
Example:
class Example {
int classVariable = 10; // Class scope
public void exampleMethod() {
int methodVariable = 20; // Method scope
if (true) {
int blockVariable = 30; // Block scope
// Accessible: classVariable, methodVariable, blockVariable
}
// Accessible: classVariable, methodVariable
// Not accessible: blockVariable
}
public void anotherMethod() {
// Accessible: classVariable
// Not accessible: methodVariable, blockVariable (from exampleMethod)
}
}
Access modifiers (public, protected, default, private) affect the accessibility of class members outside the class, but do not influence their scope within the class.