Java Naming Conventions: The Points You Must Know

Ayan Dutta
5 min readFeb 1, 2024

--

Photo by Tim Wildsmith on Unsplash

Java’s readability and maintainability are significantly enhanced by following a consistent set of naming conventions. These conventions facilitate intuitive understanding and scalability of the code. This enriched guide delves into Java naming conventions, supplemented with multiple examples and JDK references.

Packages

Packages organize related classes and interfaces, ensuring a unique namespace. The convention is all lowercase letters, with a single word post each dot, often starting with a reversed top-level domain.

JDK Examples:

  1. java.util - Contains collections framework, legacy collection classes, event model, date and time facilities.
  2. java.net - Provides the classes for implementing networking applications.

Classes

Classes are named in UpperCamelCase, with each internal word’s first letter capitalized. Class names should be nouns, indicative of the class’s purpose.

JDK Examples:

  1. ArrayList - Resizable array implementation of the List interface.
  2. ThreadLocal - Enables thread-local variables.

Interfaces

Interface names are usually adjectives in UpperCamelCase, describing a capability. Nouns are used for interfaces that represent a family of classes.

JDK Examples:

  1. Serializable - Enables object serialization.
  2. Cloneable - Indicates that a class's instances can be cloned.

Methods

Method names should be verbs or verb phrases in lowerCamelCase, clearly reflecting the action performed.

JDK Examples:

  1. charAt in String - Returns the char value at the specified index.
  2. putAll in Map - Copies all of the mappings from the specified map to this map.
chartAt method in String Class

Variables

Variables follow the lowerCamelCase convention, with the name indicating the variable’s purpose or content.

JDK Examples:

  1. elementData in ArrayList - Stores the list's elements.
  2. capacityIncrement in Vector - Amount by which the capacity is increased when the vector overflows.

Constants

Constants use uppercase letters with underscores separating words, making them stand out.

JDK Examples:

  1. MIN_VALUE in Integer - A constant holding the minimum value an int can have.
  2. MAX_PRIORITY in Thread - The maximum priority that a thread can have.

Abstract Classes

Abstract class names often start with Abstract, indicating a base implementation that requires extension. Please remember ,starting the name of an abstract class with “Abstract” is not mandatory in Java, but it is a widely adopted convention. This practice helps in enhancing the readability and understandability of the code.

JDK Examples:

  1. AbstractMap and AbstractList are two abstract classes provided by the Java Collections Framework in the java.util package. These classes are designed to provide skeletal implementations of the Map and List interfaces, respectively, to minimize the effort required to implement these interfaces.
  2. Number: This abstract class is a part of the java.lang package and serves as the superclass of classes such as BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
  3. HttpServlet: This abstract class from the javax.servlet.http package serves as the base class for HTTP servlets. It provides methods like doGet, doPost, etc., to handle HTTP requests.

Exception Classes

Exception names end with Exception, clarifying their role in error handling.

JDK Examples:

  1. IOException - Signals an I/O exception of some sort.
  2. ClassNotFoundException - Thrown when an application tries to load a class through its string name but no definition for the class with the specified name could be found.

Enumerations

  1. Enum Names: Enum types should be named using singular nouns in UpperCamelCase (also known as PascalCase), reflecting what the enumeration represents.
  2. Enum Constants: The names of enum constants should be in all uppercase letters. When enum constants consist of multiple words, they are separated by underscores.

JDK Examples:

  1. Enum TimeUnit
public enum FileOperation {
READ_FILE,
WRITE_FILE,
DELETE_FILE,
COPY_FILE,
MOVE_FILE
}

2. Enum FileOperation

public enum FileOperation {
READ_FILE,
WRITE_FILE,
DELETE_FILE,
COPY_FILE,
MOVE_FILE
}

Generic Types

Generic types are single uppercase letters, with T commonly used for a generic type. Other letters are used for specific purposes in the JDK.

JDK Examples:

  1. Map<K,V> - Represents a mapping from keys of type K to values of type V.
  2. Class<T> - The Class object that represents the runtime class of this object.

Annotations

Annotations are named in UpperCamelCase, with their functionality guiding whether they are adjectives, verbs, or nouns.

JDK Examples:

  1. @Deprecated - Indicates that the marked element is deprecated and should no longer be used.
  2. @SuppressWarnings - Tells the compiler to suppress specific warnings.

By adhering to these naming conventions and studying the provided examples, developers can enhance the readability, maintainability, and scalability of their Java code. The JDK serves as an excellent resource for understanding and applying these best practices in real-world programming scenarios.

Best Practices

  1. Descriptive Names: Choose names that clearly and succinctly describe the entity’s purpose or behavior. For instance, calculateTotalSalary() is preferable over calculate() as it precisely conveys the method's functionality.
  2. Avoid Ambiguity: Ensure that names don’t create confusion or ambiguity about an entity’s role. For example, a variable named list could be more descriptively named customerList or productList to clarify its content.
  3. Consistency: Be consistent in naming conventions across the codebase. If you use get for accessor methods, stick with it throughout (e.g., getUsername(), not fetchUsername() in one place and retrieveUsername() in another).
  4. Length vs. Clarity: While brevity is appreciated, clarity should never be compromised. A longer, descriptive name (findUserByUsername) is always better than a cryptic short one (fub).
  5. Use Domain-Specific Names: Where applicable, use names familiar within the domain of the application. For example, in a banking application, terms like deposit, withdraw, and balance are more intuitive than generic terms like add, subtract, and amount.

Anti-Patterns

  1. Overly Short or Vague Names: Names like a, temp, or data provide little to no context about the entity's purpose, leading to confusion. For example, a variable named temp could hold anything from a temperature reading to a temporary counter.
  2. Misleading Names: Names that mislead developers about an entity’s purpose can lead to erroneous assumptions and bugs. For instance, naming a method that retrieves data from a database processData might lead developers to think it also manipulates the data.
  3. Over-Abbreviation: While abbreviations can shorten names, excessive use can make names cryptic (e.g., genRptDtFrUsr for generateReportDateForUser). If abbreviations are not universally understood, they hinder readability.
  4. Hungarian Notation and Type Encoding: Prefixing variable names with type information (e.g., iCount for an integer count) is redundant in Java due to its strong type system and IDE capabilities. This practice, known as Hungarian notation, clutters the code without providing significant benefits.
  5. Inconsistent Naming: Fluctuating between naming styles (e.g., using both camelCase and snake_case in a Java codebase) can disrupt the code's visual flow and make it harder to search and maintain.

Conclusion

Java naming conventions is not merely about following a set of rules; it’s about writing code that is intuitive, maintainable, and scalable. By embracing these conventions, developers ensure their code is accessible not only to themselves but to others who may work on the codebase in the future. The JDK examples provided serve as a practical reference, illustrating how these conventions are applied in real-world Java applications.

Thanks for reading!! If you have enjoyed it, please Clap & Share it!!If you found this article valuable and would like to read more of my work, consider following me on Medium for regular updates.

--

--