Although these are not hardcore rules, it is best to follow these practices while writing code.
1. Java Packages Naming Conventions
- The package name should be in a small case.
- In case there are multiple words, separate them by a dot.
- The prefix should be one of the top-level domain names like com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries. (In, Us, Uk)
Example :
1 |
package com.journaldev.util; |
2. Classes and Interfaces Naming Conventions
- Class and Interface names should be nouns.
- They can be in mixed case but the first letter of each internal word should be capitalized. That means the first letter of the class and interface name should be capital too.
- Avoid acronyms and abbreviations.
Example :
1 2 3 4 5 6 7 8 |
public class Vehicle { //code } class CarCleaningShop { } |
3. Java Methods Naming Convention
- Methods should be verbs indicative of the functionality of that particular method.
- They can be in mixed case.
- The first letter should be in lowercase with every subsequent word having the first letter in uppercase.
Example :
1 2 3 4 5 6 7 |
void slowDown() { //code } void getCustomerAddress() { } |
4. Java Variables Naming Conventions
- Variable names should not start with an underscore (_) or dollar sign ($) characters.
- Start variable names with a lowercase letter with every subsequent word having the first letter in uppercase.
- Avoid using One-character (i,j,k) variable names except in case of temporary throwaway variables.
- Variable name should be indicative of the variable’s use.
1 2 3 4 5 6 7 8 |
public class Vehicle { public void slowDown() { int speed; int timeToStop; } } |
5. Constants Naming Conventions
- A constant name should be in all uppercase.
- In case there are multiple words, separate them by underscores (“_”).
Example :
1 2 3 4 5 |
public class Vehicle { static final int MAX_SPEED = 120; } |
Conclusion
These are the naming conventions that will make your Java code easy to read. It is not necessary to use these, however, when writing code for production that is going to be read by other people it is best to use Java naming conventions.