Post

Naming convention in Java



What is the naming convention?

A naming convention is a set of rules and guidelines used to define the names of elements in software development, such as variables, functions, classes, and more. Naming conventions are essential in programming to make code more readable, maintainable, and understandable, both for the original developers and for others who may work with the code in the future.

Common styles

First let’s take a look at the common styles, and then consider how they apply to the elements:

Style Example with ‘test’ Example with ‘mytest’
Camel case test myTest
Pascal case Test MyTest
Screaming snake case TEST MY_TEST
Kebab case test my-test
Lower case test mytest
Upper case TEST MYTEST

Java naming convention

The Java community follows several naming conventions for different elements in Java code:

  1. Projects: While there are no strict rules for project names, it is recommended to use either kebab-case or PascalCase. For example: my-project or MyProject.
  2. Packages: Package names should be in lowercase and follow a reverse domain name structure. For example, if your company’s domain is “example.com,” your package names should start with com.example.
  3. Classes: Class names should follow the PascalCase convention, for example: PersonInfo, DatabaseConnection.
  4. Interfaces: Interface names should also follow the PascalCase convention, for example: Serializable, AutoCloseable.
  5. Methods: Method names should follow the camelCase convention, for example: calculate(), getUserById().
  6. Variables: Variable names, except constants, should also follow the camelCase convention, for example: int itemCount, String userName.
  7. Constants: Constants should be declared in SCREAMING_SNAKE_CASE. For example: static final int MAX_VALUE = 100, public static final String API_KEY = "your_api_key".
  8. Enums: Enum types should follow the SCREAMING_SNAKE_CASE convention, for example: enum Color { RED, GREEN, BLUE }.
  9. Annotations: Annotation names should also follow the PascalCase convention and be nouns or noun phrases, for example: @Override, @SuppressWarnings, @Entity.

It is allowed to use well-known abbreviations in the names of classes, interfaces, methods, for example:

  • public class HTTPStatus {…} ,
  • String dbURL = "jdbc:mysql://localhost:3306/mydb",
  • public String parseXML(String xmlData) {…}
Remember, the names of all 'elements' should be meaningful and indicate their purpose. Avoid single-letter or ambiguous names. Following the rules is a good programming practice that helps improve the readability and maintainability of your code.
This post is licensed under CC BY 4.0 by the author.