Junior
What scopes can be used in any application?
sobes.tech AI
Answer from AI
In Java, the following scopes can be used:
- Class (static): Variables and methods declared as
static. They are associated with the class rather than an instance of the object. Accessible through the class name. - Instance: Variables and methods that are not
static. They are associated with a specific instance of the object. Accessible only after creating an object. - Method (local): Variables declared inside a method, constructor, or initialization block. Accessible only within the block of code where they are declared.
- Block: Variables declared inside any block
{}, such as infor,whileloops,if,elsestatements. Accessible only within that block.
// Class scope (static)
public class ExampleClass {
static int classVariable = 10; // Class (static) scope
// Instance scope
int instanceVariable = 20; // Instance scope
public void exampleMethod() {
// Method scope
int methodVariable = 30; // Method scope
if (true) {
// Block scope
int blockVariable = 40; // Block scope
System.out.println(blockVariable); // Accessible
}
// System.out.println(blockVariable); // Not accessible here
System.out.println(methodVariable); // Accessible
System.out.println(instanceVariable); // Accessible
System.out.println(classVariable); // Accessible
}
public static void main(String[] args) {
System.out.println(classVariable); // Accessible directly through class name
// System.out.println(instanceVariable); // Not accessible directly, needs an object
// System.out.println(methodVariable); // Not accessible
// System.out.println(blockVariable); // Not accessible
ExampleClass obj = new ExampleClass();
System.out.println(obj.instanceVariable); // Accessible through object
}
}