Java Strings, Generics, Collections, Exceptions, Enums and Annotations Best Practices

In this article, I would like to discuss the Java best practices of important and most commonly used Java topics Strings, Generics, Collections, Exceptions, Enums, and Annotations.

In this article, I have summarized the best practices and there is a separate article to demonstrate each Java best practice with an example.

Let's get started!.

Java String Best Practices

  1. Use StringBuilder or StringBuffer for string concatenations instead of the + operator.
  2. Compare two string by equals() Method instead == operator
  3. Call .equals() method on known string constants rather than unknown variable
  4. Prefer switch( ) statement instead of multiple if-else-if.
  5. Use String.valueOf() instead of toString()
  6. Prefer StringUtility classes from different popular libraries because these utility classes are tested and well-known libraries.
  7. Avoid Duplicate Literals - Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
  8. Using equalsIgnoreCase() is faster than using toUpperCase() or toLowerCase().equals()
  9. Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
  10. Consecutive calls to StringBuffer/StringBuilder.append should be chained, reusing the target object. This can improve the performance by producing a smaller bytecode, reducing overhead and improving inlining.
Each of the above String best practices are demonstrated with examples at Guide to String Best Practices in Java.

Java Collection Framework Best Practices

  1. Choosing the right collection/map
  2. Code for an interface, not for implementation
  3. Use generic type and diamond operator
  4. Prefer isEmpty() over a size()
  5. Return empty collections or arrays, not nulls
  6. Do not use the classic for loop
  7. Favor using forEach() with Lambda expressions
  8. Override equals() and hashCode() properly
  9. Implementing the Comparable interface properly
  10. Using  Arrays and Collections utility classes
  11. Prefer concurrent collections over synchronized wrappers
  12. Use EnumSet instead of bit fields
  13. Use EnumMap instead of ordinal indexing
  14. Eliminate unchecked warnings

Each of the above Collections framework best practices are demonstrated with examples at Guide to String Best Practices in Java.

Java Exception Handling Best Practices

  1. Clean up resources in a finally block or use a Try-With-Resource Statement
  2. Throw Specific Exception
  3. Do not catch the Exception class rather catch specific subclasses
  4. Never catch a Throwable class
  5. Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost
  6. Catch the most specific exception first
  7. Don’t ignore exceptions rather log the exceptions
  8. Never throw any exception from finally block
  9. Don’t use printStackTrace() statement or similar methods
  10. Use finally blocks instead of catch blocks if you are not going to handle the exception
  11. Validate user input to catch adverse conditions very early in request processing
  12. Throw exceptions with descriptive messages
Each of the above exception handling best practices demonstrated with examples at Java Collection Framework Best Practices

Java Generics Best Practices

  1. Don’t use raw types
  2. Eliminate unchecked warnings
  3. Prefer Lists to Arrays
  4. Favor Generic Types
  5. Favor generic methods
  6. Use Bounded Wildcards to Increase API Flexibility
  7. Combine Generics and varargs Judiciously
  8. Consider typesafe heterogeneous containers
Each of the above Generics best practices demonstrated with examples at Java Generics Best Practices

Java Enums and Annotations Best Practices

  1. Use enums instead of int constants
  2. Use instance fields instead of ordinals
  3. Use EnumSet instead of bit fields
  4. Use EnumMap instead of ordinal indexing
  5. Emulate extensible enums with interfaces
  6. Prefer annotations to name patterns
  7. Consistently use the Override annotation
  8. Use marker interfaces to define types
Each of the above enums and annotations best practices demonstrated with examples at Java Enums and Annotations Best Practices

Java Serialization Best Practices

  1. Enable serialization compatibility during class evolution
  2. Do not deviate from the proper signatures of serialization methods
  3. Do not serialize unencrypted sensitive data
  4. Do not serialize instances of inner classes
  5. Do not invoke overridable methods from the readObject() method
  6. Avoid memory and resource leaks during serialization
  7. Prevent overwriting of externalizable objects
  8. Prevent deserialization of untrusted data
  9. Declare an explicit serial version UID in every serialization class you write
Each of the above Serialization best practices demonstrated with examples at Java Synchronization Best Practices

Java Standard Naming Conventions

We should follow these Java naming conventions in the day to day project work.
Let's discuss package, class, variable, method, constant, abstract class and exception class naming conventions with examples at Java Standard Naming Conventions