Junior — Middle
Where is the static field located in the class and how does it work?
sobes.tech AI
Answer from AI
A static field in a Java class is declared with the keyword static and is located inside the class body but outside of methods and constructors. It belongs to the class itself, not to any specific object, so it exists as a single instance for all objects of that class.
This means that all instances of the class share the same static field. Changing the value of the static field through one object affects all others.
Example:
public class Example {
static int counter = 0; // static field
public Example() {
counter++; // increment counter when creating an object
}
}
// Usage:
Example a = new Example();
Example b = new Example();
System.out.println(Example.counter); // Will output 2
Static fields are often used to store common data or constants accessible without creating an instance of the class.