Java Coding Standards
A comprehensive style and quality guide based on the Google Java Style Guide and
Oracle conventions
1. Purpose and Scope
This document defines conventions for writing maintainable, consistent Java code across an
engineering organization. Java's verbosity and strong typing make disciplined structure especially
valuable for long-lived codebases. These guidelines are based on the Google Java Style Guide and
Oracle's long-standing Java code conventions, which together represent the most widely referenced
standards in the Java ecosystem.
2. Naming Conventions
Element Convention
Classes / Interfaces PascalCase (e.g., UserService)
Methods / variables camelCase (e.g., getUserById())
Constants UPPER_SNAKE_CASE (e.g., static final int MAX_SIZE)
Packages all lowercase, reverse domain (e.g., [Link])
Type parameters (generics) single uppercase letter, e.g., T, E, K, V
Enum constants UPPER_SNAKE_CASE (e.g., ORDER_PLACED)
3. Formatting
• Indent with 2 or 4 spaces consistently across the project (Google style uses 2; Oracle historically
uses 4).
• Opening brace on the same line as the declaration (K&R; style).
• One statement per line; limit lines to roughly 100–120 characters.
• Use a single blank line to separate logical blocks within a method.
• Order class members consistently: static fields, instance fields, constructors, methods.
4. Example Class
public class UserService {
private static final int MAX_RETRIES = 3;
private final UserRepository repository;
public UserService(UserRepository repository) {
[Link] = repository;
public User getUserById(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Invalid id");
return [Link](id);
5. Class and Method Design
• Follow the single responsibility principle — one class, one clear purpose.
• Prefer composition over inheritance where practical to reduce coupling.
• Keep methods short and focused; extract helper methods for complex or repeated logic.
• Mark fields private by default; expose behavior via well-named public methods rather than raw
setters where possible.
• Favor immutability: mark fields final where they don't need to change after construction.
6. Error Handling
• Avoid catching generic Exception or Throwable; catch specific exception types.
• Use checked exceptions for recoverable conditions the caller should handle, and unchecked
exceptions for programming errors.
• Never leave empty catch blocks; at minimum log with enough context to diagnose the issue.
• Prefer try-with-resources for any AutoCloseable resource (streams, connections, readers).
• Fail fast: validate arguments at the start of a method rather than deep inside logic.
6.1 Example
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return [Link]();
} catch (IOException e) {
[Link]("Failed to read file: {}", path, e);
throw new ServiceException("Unable to read configuration", e);
7. Documentation
• Use Javadoc comments for all public classes, interfaces, and methods.
• Document the purpose, parameters, return values, and exceptions thrown for non-trivial methods.
• Keep inline comments focused on explaining *why*, not restating *what* the code already shows.
• Generate and review Javadoc output periodically to catch broken or stale documentation.
8. Testing Standards
• Use JUnit (5.x) as the standard testing framework unless a project has an established alternative.
• Name test classes Test and test methods descriptively (e.g., shouldThrowWhenIdIsInvalid).
• Use Mockito or an equivalent for mocking dependencies in unit tests.
• Keep unit tests fast and isolated; reserve database/network calls for integration tests.
• Aim for meaningful coverage of business logic and edge cases rather than a raw percentage
target.
9. Security Considerations
• Never hardcode credentials, API keys, or secrets in source code; use environment variables or a
secrets manager.
• Use PreparedStatement (or an ORM's parameterized queries) to prevent SQL injection — never
concatenate raw input into SQL.
• Validate all external input at trust boundaries (API layer, file parsing, deserialization).
• Keep dependencies current and monitor for known CVEs using tools like OWASP
Dependency-Check.
• Avoid deserializing untrusted data with Java's native serialization mechanism.
10. Common Pitfalls
• Comparing objects (including boxed types like Integer) with == instead of .equals().
• Not overriding equals() and hashCode() together, breaking collections that rely on them.
• Leaking resources by not closing streams, connections, or readers.
• Overusing checked exceptions for conditions that aren't truly recoverable, cluttering method
signatures.
• Mutable static state causing subtle bugs in multi-threaded contexts.
11. Tooling and Automation
• Enforce formatting with google-java-format or an equivalent to remove style debates from review.
• Use Checkstyle or SpotBugs to catch style violations and likely bugs automatically.
• Run static analysis (e.g., SonarQube) as part of CI to track code quality trends over time.
• Use a build tool (Maven or Gradle) with a locked, reproducible dependency configuration.
12. Version Control and Code Review
• Write commit messages describing intent, referencing ticket/issue numbers where applicable.
• Keep pull requests focused on a single logical change to keep review manageable.
• Require passing tests and at least one approving review before merge.
• Reviewers should check for thread-safety, resource handling, and adherence to these
conventions.
13. Summary Checklist
• Consistent PascalCase / camelCase / UPPER_SNAKE_CASE naming.
• Formatted with google-java-format, checked with Checkstyle/SpotBugs.
• Javadoc present on public APIs.
• Specific exception handling, resources closed via try-with-resources.
• Unit tests written with JUnit and passing in CI.
• No secrets committed to source control.
Compiled as an original summary of widely-followed community and vendor style guidelines, for internal reference use.