Java / Java 21 Coding Standards Interview Questions
Explain the standard structure and member ordering of a Java class file?
Standard style guides fix a consistent top-to-bottom order so any file can be scanned the same way: package declaration, imports (grouped and sorted), Javadoc and class declaration, then static fields, instance fields, constructors, and finally methods.
public class OrderService { private static final int MAX_RETRIES = 3; // static fields private final OrderRepository repository; // instance fields public OrderService(OrderRepository repository) { ... } // constructors public Order create(OrderRequest request) { ... } // public methods private void validate(OrderRequest request) { ... } // private helpers }
Within the methods section, the convention is public methods first, in roughly the order a caller would use them, followed by private helper methods placed near the public method that calls them rather than alphabetized or grouped separately - this keeps related logic visually close together.
Nested types and enums are typically placed at the very end of the class, after all fields and methods, so a reader encountering the top of the file first sees the class's public contract before its internal supporting details.
More Related questions...