Java / Java 21 Coding Standards Interview Questions
1. What is a coding standard in Java, and why does it matter for Java 21 projects?
A coding standard is a documented set of rules covering naming, formatting, structure, and idioms that every developer on a team follows when writing Java code. It removes personal style from the equation so that any two files in the codebase read as if one person wrote them. In a Java 21 codebas...
2. What are the standard naming conventions for classes and interfaces in Java 21?
Classes and interfaces are named in UpperCamelCase , using nouns or noun phrases that describe what the type represents, such as OrderProcessor or PaymentGateway . This convention is unchanged in Java 21, but it now also applies to two newer type declarations: records and sealed types. A record s...
3. What are the standard naming conventions for methods and variables in Java?
Methods and variables use lowerCamelCase . Method names should be verbs or verb phrases that describe the action performed, such as calculateTotal() or isEligible() , while variable names should be nouns that describe the data they hold, such as orderCount or customerName . Boolean methods and va...
4. What is the purpose of a static analysis tool like Checkstyle in a Java 21 codebase?
Checkstyle scans source files against a configured rule set - naming patterns, import order, line length, brace placement, and Javadoc presence - and fails the build when a file violates one of them, before a human reviewer ever opens the file. Its purpose is to make style enforcement automatic a...
5. What is a record in Java 21, and why do coding standards recommend it for data carriers?
A record is a special class declaration that compresses a data carrier down to its essential fields; the compiler generates the constructor, accessors, equals() , hashCode() , and toString() automatically from the declared components. public record OrderLine(String sku, int quantity, BigDecimal u...
6. What is a text block in Java 21?
A text block is a multi-line string literal delimited by triple double quotes ( """ ) that lets a chunk of text such as JSON, SQL, or HTML be written in the source file exactly as it should appear, without escape sequences for quotes or explicit newline characters. S tr i n g jso n = """ { " na m...
7. Define var and explain the coding standard guidelines around its use in Java 21?
var tells the compiler to infer a local variable's type from the expression on the right-hand side at compile time; it is not a dynamic type and the variable is still statically typed once inferred. var orders = new ArrayList < Order > (); // inferred as ArrayList
8. What are sealed classes in Java 21?
A sealed class or interface restricts which other classes are allowed to extend or implement it, using a permits clause that lists the exact set of allowed subtypes. public sealed interface Shape permits Circle, Square, Triangle {} public final class Circle implements Shape { /* ... */ } Each per...
9. Describe the recommended package naming convention in Java style guides?
Package names are written entirely in lowercase, with no underscores or camelCase, and follow the reversed-domain pattern such as com.company.project.module . Lowercase avoids any collision with class names, which start with an uppercase letter by convention. Beneath the reversed-domain root, pac...
10. List the common Javadoc conventions required in Java coding standards?
Javadoc conventions define what must be documented and how the comment is written so generated API docs stay useful: Every public class, interface, and public method has a Javadoc comment describing its purpose in a single leading sentence. @param is included for every parameter, describing what ...
11. What is the purpose of the @Override annotation in Java coding standards?
@Override tells the compiler that a method is intended to override a superclass method or implement an interface method. If the signature does not actually match one being overridden, compilation fails immediately instead of silently creating an unrelated overloaded method. @Override public Strin...
12. What are the types of comments recommended in Java style guides?
Java style guides recognize three categories of comments, each with a distinct purpose: Type Purpose Javadoc ( /** ... */ ) Documents the public contract of a class or method for external callers and generated API docs. Block comment ( /* ... */ ) Explains a non-obvious algorithm or a workaround,...
13. How do you format a pattern-matching switch expression per Java 21 coding standards?
A pattern-matching switch is written as an expression using arrow syntax, with each case testing a type pattern rather than a constant, and the result assigned directly instead of through a mutable local variable. String describe(Object obj) { return switch (obj) { case Integer i when i > 0 -> "p...
14. What is the purpose of the final keyword in Java 21 coding standards?
final marks a variable, field, parameter, method, or class as unable to be reassigned or, for methods and classes, unable to be overridden or extended. On a local variable or field it means the reference is set once and never changed again. public final class Money { private final BigDecimal amou...
15. How do you apply consistent indentation and brace style in Java 21 code?
Most Java style guides use four-space indentation (no tabs) and Kernighan-and-Ritchie style braces, where the opening brace stays on the same line as the declaration and the closing brace lines up with the start of that declaration. public void processOrder(Order order) { if (order.isValid()) { s...
16. What is the purpose of pattern matching for instanceof in Java 21?
Pattern matching for instanceof combines the type check and the cast into a single expression: if the check succeeds, the compiler automatically binds the value to a new, correctly typed variable in the surrounding scope. if (obj instanceof String s && ! s.isBlank()) { System.out.println(s.trim()...
17. Describe the standard naming convention for custom exception classes in Java?
A custom exception class is named as a noun phrase ending in Exception , describing the specific failure it represents, such as InsufficientFundsException or OrderNotFoundException , rather than a vague name like AppException or ErrorType1 . public class OrderNotFoundException extends RuntimeExce...
18. What are the recommended import ordering rules in Java coding standards?
Imports are grouped and each group is sorted alphabetically: java.* packages first, then javax.* , then third-party libraries, then the project's own packages, with a blank line separating each group. import java.util.List ; import java.util.Map ; import javax.annotation.Nullable ; import com.fas...
19. Why is a record preferred over a traditional POJO for immutable data carriers?
A hand-written immutable POJO needs a constructor, private final fields, getters, and correct equals() / hashCode() / toString() implementations - five separate places where a forgotten field or a mismatched implementation can introduce a bug, for example an equals() that checks three fields whil...
20. How does pattern matching for switch change the coding standard for type-checking code?
Before pattern matching, a type-dispatch chain was typically written as a series of instanceof checks with explicit casts inside an if / else if ladder, and nothing forced the author to handle every known subtype. // old style if (shape instanceof Circle) { Circle c = (Circle) shape; return Math....
21. What is the difference between var and explicit typing under Java 21 style guides?
var and explicit typing produce identical bytecode and identical static type safety - the difference is purely about what the reader sees at the declaration site, not about behavior or performance. var Explicit type Type is inferred from the initializer at compile time. Type is written out and en...
22. Why should you avoid wildcard imports in Java 21 projects?
A wildcard import such as import java.util.*; pulls in every public type from that package without listing which ones are actually used, so a reader cannot tell from the import list alone where a given class in the file comes from. It also creates a fragile dependency on package contents: if two ...
23. How do you troubleshoot a NullPointerException using Objects.requireNonNull as a coding standard?
The standard practice is to validate constructor and setter arguments with Objects.requireNonNull(value, "message") at the boundary where the value enters the object, rather than letting a null quietly propagate until it is dereferenced several calls later, far from its actual source. public Orde...
24. Why doesn't Checkstyle allow tab characters in most Java 21 style guides?
A tab character renders at a different visual width depending on the editor's tab-size setting, so a file that looks correctly indented in one developer's editor can look misaligned in another's, even though the underlying bytes are identical. This becomes a real problem in diffs and code review:...
25. When should you use a sealed interface instead of an enum?
An enum fits when every variant is a simple, stateless (or identically-shaped) constant - DayOfWeek or Status are classic examples, where each value needs no unique fields beyond what every other value also has. public sealed interface PaymentMethod permits CreditCard, BankTransfer {} public reco...
26. What happens when you omit a break statement in a traditional switch under coding standards?
In a traditional colon-style switch , omitting break causes execution to fall through into the next case's statements, continuing until a break , return , or the end of the switch block is reached - a behavior that is easy to trigger by accident. switch (level) { case LOW: System.out.println( "lo...
27. How is exception handling standardized in Java 21 with multi-catch and try-with-resources?
Multi-catch lets a single catch block handle several unrelated exception types with identical recovery logic, avoiding duplicated catch blocks that differ only in the exception type they name. try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { ...
28. Why is virtual thread naming convention different from platform thread naming?
Platform threads are few in number and long-lived, so giving each one a distinct, meaningful name like db-connection-pool-3 is cheap and genuinely useful for identifying it in a thread dump. Thread.ofVirtual().name("order-worker-", 0).start(task); // numbered, not individually hand-named Virtual ...
29. When should you choose text blocks over string concatenation?
A text block is the standard choice once a string literal spans more than roughly two or three lines, or contains embedded quotes, because concatenation with + and escaped \" characters quickly becomes hard to read and easy to get subtly wrong. // concatenation String sql = "SELECT id, name " + "...
30. How do you optimize import statements and static imports per a Java style guide?
Optimizing imports starts with removing anything unused - most IDEs offer an "optimize imports" action that deletes dead imports and collapses duplicate ones automatically as part of a pre-commit or save action. import static java . util . stream . Collectors . toList; import static org . junit ....
31. What is the difference between checked and unchecked exceptions under Java coding standards?
Checked exception Unchecked exception Extends Exception (not RuntimeException); the compiler forces callers to catch or declare it. Extends RuntimeException; the compiler does not require handling. Used for recoverable, expected failures the caller can reasonably act on. Used for programming erro...
32. Why should you prefer immutable records over mutable classes for DTOs?
A mutable DTO can be modified after it is handed off - passed into a method, stored in a cache, or shared across threads - meaning the object a caller holds a reference to may no longer represent what it originally received, which is a frequent source of hard-to-trace bugs. public record Customer...
33. 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 ...
34. Which is better and why: an enhanced switch or an if-else chain for type checks?
Enhanced switch if-else chain Compiler checks exhaustiveness when matching a sealed type. No compiler check; a missing branch is silent until it runs. Reads as a single expression producing one value. Reads as a sequence of independent statements. Scales cleanly to many variants. Becomes harder t...
35. How do you apply the Single Responsibility Principle in Java 21 class design standards?
The Single Responsibility Principle says a class should have exactly one reason to change; in practice this means separating "what the data is" from "what happens to it" and from "how it is delivered or persisted". public record Invoice (String id, BigDecimal total) {} // data public class Invoic...
36. Explain the lifecycle of a virtual thread under Java 21 coding standard recommendations?
A virtual thread is created via Thread.ofVirtual() or Executors.newVirtualThreadPerTaskExecutor() , and it moves through the same conceptual states as a platform thread - new, runnable, running, waiting or blocked, and terminated - but the JVM, not the OS, schedules it onto a small pool of carrie...
37. Explain the execution flow of a switch expression using guarded patterns?
When a switch expression evaluates its selector, it tests cases top to bottom; a guarded pattern ( case Type t when condition -> ) only matches if both the type pattern binds successfully and the guard condition evaluates to true, otherwise evaluation falls through to the next case. flowchart TD ...
38. Explain the internal working of sealed class exhaustiveness checking by the compiler?
When a switch matches on a type declared sealed , the compiler reads that type's permits clause to obtain the complete, closed list of allowed subtypes - information it cannot get from an open class or interface, which could be extended by any code anywhere. flowchart TD A[Compile switch over sea...
39. How can you optimize code readability using record patterns and deconstruction?
A record pattern lets a switch or instanceof check destructure a record's components directly in the pattern itself, binding each component to a named variable in one step instead of matching the record and then calling its accessors separately. flowchart LR A["case Point(int x, int y) when x == ...
40. How do you troubleshoot deprecated API usage flagged by Java 21 standards tooling?
When the compiler or a linter flags @Deprecated usage, the first step is reading the annotation's own Javadoc and since / forRemoval attributes, since forRemoval = true signals the API will actually disappear in a future release, not merely fall out of favor. @Deprecated (since = "9" , forRemoval...
41. Why is structured concurrency recommended over raw thread management in Java 21?
Structured concurrency (a preview feature in Java 21 via StructuredTaskScope ) treats a group of related subtasks as a single unit of work: if one subtask fails, the others are cancelled, and the parent does not proceed until every child has either completed or been cancelled. sequenceDiagram par...
42. What is the difference between synchronized blocks and virtual-thread-friendly designs?
synchronized block Virtual-thread-friendly design Historically pins the carrier thread for the block's duration when used on a virtual thread. Uses java.util.concurrent locks, which release the carrier thread while waiting. A pinned carrier thread cannot run any other virtual thread meanwhile. Ca...
43. How does the compiler enforce exhaustiveness in a switch over sealed types?
Exhaustiveness enforcement is a two-part compile-time check: first, the compiler resolves the full, closed set of permitted subtypes from the sealed type's declaration; second, it verifies that the switch 's cases, taken together, cover every member of that set with no gaps. sealed interface Shap...
44. Why should you avoid finalizers in favor of try-with-resources under Java 21 standards?
Object.finalize() has been deprecated for removal since Java 9 because its execution timing is entirely unpredictable - the garbage collector decides if and when a finalizer runs, so resource cleanup could be delayed indefinitely or, in some cases, never happen before the JVM exits. // avoid prot...
45. Explain the internal working of the Sequenced Collections API introduced in Java 21?
The Sequenced Collections API adds a common supertype, SequencedCollection , that any collection with a well-defined encounter order can implement, providing uniform methods for first/last access and reversal without each collection type inventing its own naming. flowchart TD A[SequencedCollectio...
46. How do you design a thread-safe class following Java 21 coding standards?
The standard starting point is to make the class immutable wherever possible - final fields set only in the constructor, no setters - since an immutable object is automatically thread-safe with no locking required, and records make this the default rather than something to opt into. public record...
47. When should you use module-info.java for encapsulation as per coding standards?
A module-info.java is warranted once a project is distributed as a reusable library or split into independently versioned components, because the Java Platform Module System lets it declare exactly which packages are exported for external use and which remain fully internal, even to other modules...
48. Which is better and why: exceptions versus sealed result types for error handling?
Exceptions Sealed result type Failure path is implicit; easy for a caller to forget to catch it. Failure is a value the caller must explicitly handle to get the success value out. Carries a stack trace, useful for unexpected/bug-like failures. No stack trace by default; best for expected, frequen...
49. How can you optimize static analysis coverage for Java 21 features like pattern matching?
Older static analysis rule sets were written before pattern matching, sealed types, and records existed, so out-of-the-box configurations often miss issues specific to them - an unguarded pattern that silently shadows a broader case, or a record whose compact constructor skips validation that the...
50. Explain the internal working of Generational ZGC and its influence on object-lifecycle coding standards?
Generational ZGC (finalized as the default ZGC mode in Java 21) splits the heap into a young generation for newly allocated objects and an old generation for objects that survive multiple collections, based on the well-established observation that most objects die young. flowchart LR A[Object all...