When working with Java code, adhere to the following:
- **Target Version:** Aim for compatibility with Java 11 (LTS) or Java 17 (LTS) or newer, unless specified otherwise by the user or project context. Prefer features available in these LTS versions.
- Explicitly state if a feature requires a more recent Java version.
- **Conventions:** Follow standard Java coding conventions (e.g., Oracle's Java Code Conventions, Google Java Style Guide).
- **Readability:**
- Use clear and descriptive names for classes, interfaces, methods, and variables (CamelCase for classes/interfaces, lowerCamelCase for methods/variables, SCREAMING_SNAKE_CASE for constants).
- Indentation: Use 4 spaces for indentation.
- Line Length: Aim for a reasonable line length (e.g., 100-120 characters).
- Brace Style: Use K&R style braces (opening brace on the same line).
- **Imports:**
- Organize imports: Java standard library, then third-party, then project-specific.
- Avoid wildcard imports (`import java.util.*;`) for public APIs; be specific.
- Remove unused imports.
- **Lambdas and Streams:** Utilize lambda expressions and the Stream API for processing collections and data where it enhances readability and conciseness.
- **`Optional`:** Use `java.util.Optional` to represent potentially absent values, avoiding null pointer exceptions. Avoid `Optional` for method parameters or fields unless absolutely necessary.
- **`java.time` API:** Use the `java.time` package (JSR 310) for all date and time operations, replacing legacy `java.util.Date` and `java.util.Calendar`.
- **`try-with-resources`:** Use `try-with-resources` for managing resources that implement `AutoCloseable` (e.g., I/O streams, database connections).
- **Records (Java 14+):** If the target Java version supports it and it's appropriate, suggest using `record` types for simple data carriers.
- **Sealed Classes/Interfaces (Java 15+):** If applicable, consider sealed classes/interfaces to control inheritance hierarchies.
- **Pattern Matching for `instanceof` (Java 14+):** Use pattern matching with `instanceof` for cleaner type checks and casts.
- **Switch Expressions (Java 12+):** Prefer switch expressions over traditional switch statements where applicable for conciseness and safety.
- **Encapsulation:** Properly encapsulate class members (use `private` by default, provide getters/setters as needed).
- **Immutability:** Prefer immutable objects where possible, especially for value objects.
- **Interfaces:** Code to interfaces rather than concrete implementations where appropriate to promote flexibility.
- **Inheritance vs. Composition:** Favor composition over inheritance (SOLID principles). Use inheritance when there's a clear "is-a" relationship and it provides genuine polymorphism.
- **SOLID Principles:** Keep SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) in mind when designing classes and methods.
- **Checked vs. Unchecked Exceptions:** Understand and use checked and unchecked exceptions appropriately.
- Use checked exceptions for recoverable conditions where the client code should be forced to handle the exception.
- Use unchecked (runtime) exceptions for programming errors (e.g., `NullPointerException`, `IllegalArgumentException`) or unrecoverable system errors.
- **Specific Exceptions:** Catch specific exceptions rather than generic `Exception` or `Throwable`.
- **Custom Exceptions:** Create custom exception classes (both checked and unchecked as appropriate) for application-specific error conditions.
- **Clear Messages:** Provide informative error messages in exceptions.
- **`finally` Block:** Use `finally` blocks for cleanup code that must always execute.
- **Avoid Swallowing Exceptions:** Do not catch an exception and then ignore it (empty catch block) without a very good reason and a comment explaining why.
- **Mandatory:** Write Javadoc comments for all public and protected classes, interfaces, methods, and fields.
- **Style:** Adhere to standard Javadoc conventions.
- Include `@param` for all parameters.
- Include `@return` for methods that return a value.
- Include `@throws` or `@exception` for any checked exceptions a method might throw.
- Include `@see` for related classes or methods.
- Include `@since` for new APIs.
- The first sentence should be a concise summary of the element.
- **Content:** Docstrings should explain *what* the code does, its parameters, what it returns, and any exceptions it might throw.
- **Use appropriate collections:** `List`, `Set`, `Map`, `Queue`, etc., based on the requirements.
- **Prefer interfaces:** Declare variables using interface types (e.g., `List<String> list = new ArrayList<>();`).
- **Generics:** Use generics correctly to ensure type safety. Avoid raw types.
- **Concurrency:** Be mindful of thread safety when using collections in concurrent environments. Use concurrent collections from `java.util.concurrent` (e.g., `ConcurrentHashMap`, `CopyOnWriteArrayList`) or proper synchronization.
- **`java.util.concurrent`:** Utilize the utilities in `java.util.concurrent` (Executors, Futures, Locks, concurrent collections) for robust concurrent programming.
- **Avoid `Thread` subclassing:** Prefer implementing `Runnable` or `Callable` and using an `ExecutorService`.
- **Synchronization:** Use `synchronized` blocks or methods judiciously. Be aware of potential deadlocks and performance implications. Prefer higher-level concurrency utilities when possible.
- **Volatile:** Understand the use of `volatile` for visibility of shared variables.
- **Assumption:** Assume projects use standard build tools like Maven or Gradle.
- **Dependency Management:** If suggesting new third-party libraries, mention they should be added to the project's `pom.xml` (Maven) or `build.gradle` (Gradle) file.
- **Standard Library First:** Prefer solutions using the Java standard library if they are adequate, before suggesting third-party packages.
- **Testability:** Write code that is easily testable (e.g., by using dependency injection, avoiding static coupling where possible).
- **Unit Testing Frameworks:** Assume the use of standard testing frameworks like JUnit or TestNG.
- **Suggestion for Tests:** If appropriate, suggest basic test cases for the code you generate, especially for utility methods or complex business logic.
- **Input Validation:** Thoroughly validate all external inputs. Be aware of common Java vulnerabilities (e.g., SQL injection if constructing queries manually, XSS in web applications, deserialization vulnerabilities).
- **Serialization:** Be extremely cautious when deserializing untrusted data. Consider alternatives or use filtering mechanisms (`java.io.ObjectInputFilter`).
- **Resource Management:** Ensure resources are properly closed (use `try-with-resources`).
- **Secure Randomness:** Use `java.security.SecureRandom` for cryptographically strong random numbers, not `java.util.Random`.
- **Raw Types:** Avoid using raw types with generic classes/interfaces.
- **`==` for String Comparison:** Use `.equals()` for comparing string content, not `==`.
- **Ignoring Return Values:** Pay attention to methods whose return values indicate success/failure or are essential (e.g., `File.delete()`, `String.replace()`).
- **Mutable Static Fields (without proper synchronization):** Be cautious with mutable static fields in concurrent environments.
- **Overuse of `null`:** Prefer `Optional` or other strategies to manage absence of values.