- Java Guides
- Table of contents
- Video
- 1. Packages naming conventions
- 2. Classes naming conventions
- 3. Interfaces naming conventions
- 4. Methods naming conventions
- 5. Variables naming conventions
- 6. Constants naming conventions
- 7. Abstract classes naming conventions
- 8. Exception classes naming conventions
- 9. Enumeration naming conventions
- 10. Generic types naming conventions
- 11. Annotations naming conventions
- Specific Naming Conventions(Good to know)
- Conclusion
- Related posts
- Naming Conventions in Java
- Naming Conventions in Java
Java Guides
Java naming conventions are sort of guidelines that application programmers are expected to follow to produce a consistent and readable code throughout the application.
Table of contents
Video
Let’s discuss package,class,variable,method,constant,abstract class and exception class naming conventions with examples.
1. Packages naming conventions
A package should be named in lowercase characters. There should be only one English word after each dot.
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.
package org.springframework.core.convert; package org.hibernate.criterion; package org.springframework.boot.actuate.audit; package org.apache.tools.ant.dispatch;
Package naming convention used by Oracle for the Java core packages. The initial package name representing the domain name must be in lower case.
package java.lang; package java.util;
2. Classes naming conventions
Class names should be nouns in UpperCamelCase (in mixed case with the first letter of each internal word capitalized). Try to keep your class names simple and descriptive.
class Employee class Student class EmployeeDao class CompanyService
class String class Color class Button class System class Thread class Character class Compiler class Number
3. Interfaces naming conventions
In Java, interfaces names, generally, should be adjectives. Interfaces should be in titlecase with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they present a family of classes e.g. List and Map.
Runnable Remote ActionListener Appendable AutoCloseable CharSequence Cloneable Comparable Readable
4. Methods naming conventions
Methods always should be verbs. They represent action and the method name should clearly state the action they perform. The method name can be single or 2-3 words as needed to clearly represent the action. Words should be in camel case notation.
Examples:
public List Customer> getCustomers(); public void saveCustomer(Customer theCustomer); public Customer getCustomer(int theId); public void deleteCustomer(int theId);
getName() computeTotalWidth() actionPerformed() main() print() println(),
5. Variables naming conventions
The variable name should start with a lowercase letter. Parameter names, member variable names, and local variable names should be written in lowerCamelCase.
firstName orderNumber lastName phoneNo id counter temp
6. Constants naming conventions
Constant variable names should be written in upper characters separated by underscores. These names should be semantically complete and clear.
RED, YELLOW, MAX_PRIORITY, MAX_STOCK_COUNT
7. Abstract classes naming conventions
I observed in many standard libraries, the naming conventions used for Abstract class is class name must start with Abstract or Base prefix. This naming convention can vary from organization to organization.
AbstractHibernateDao AbstractCommonDao AbstractBase
AbstractBean AbstractBeanDefinition AbstractUrlBasedView AbstractIdentifiable
8. Exception classes naming conventions
I observed in many standard libraries, the naming conventions used for custom Exception class is class name must end with Exception suffix.
TransactionException SQLDataException ResourceNotFountException ResourceAlreadyExistException
ArithmeticException ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassNotFoundException CloneNotSupportedException EnumConstantNotPresentException Exception IllegalAccessException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException
9. Enumeration naming conventions
public enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; >
10. Generic types naming conventions
Generic type parameter names should be uppercase single letters. The letter ‘T’ for a type is typically recommended. In JDK classes, E is used for collection elements, S is used for service loaders, and K and V are used for map keys and values.
public interface Map <> public interface List extends CollectionE> <> IteratorE> iterator() <>
11. Annotations naming conventions
Annotation names follow title case notation. They can be adjective, verb or noun based on the requirements.
public @interface FunctionalInterface <> public @interface Deprecated <> public @interface Documented <> public @Async Documented < public @Test DocumentedSpecific Naming Conventions(Good to know)
Apart from the above java standard naming conventions, there are few more naming conventions that would be followed in many standard libraries such as Spring, Apache, Hibernate etc.
isSet, isVisible, isFinished, isFound, isOpenThis is the naming convention for boolean methods and variables used by Oracle for the Java core packages.
Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to choose more meaningful names.
void setFound(boolean isFound);There are a few alternatives to the is a prefix that fits better in some situations. These have, can and should prefixes:
boolean hasLicense(); boolean canEvaluate(); boolean shouldAbort = false;valueSet.computeAverage(); matrix.computeInverse()Give the reader the immediate clue that this is a potentially time-consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.
vertex.findNearestVertex(); matrix.findSmallestElement(); node.findShortestPath(Node destinationNode);Give the reader the immediate clue that this is a simple lookup method with a minimum of computations involved. Consistent use of the term enhances readability.
CollectionPoint> points; int[] values;Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.
void setTopic(Topic topic) // NOT: void setTopic(Topic value) // NOT: void setTopic(Topic aTopic) // NOT: void setTopic(Topic t) void connect(Database database) // NOT: void connect(Database db) // NOT: void connect(Database oracleDB)line.getLength(); // NOT: line.getLineLength();Please write comments, if you want to give any suggestions or feedback about my articles would be appreciated.
If you like my articles and want similar kind of stuff, connect with me on Google +, Facebook, GitHub, and StackOverflow.
Check out our top viewed Java Guides and Java/J2EE Best practices. I hope you like it.
Happy Learning and Keep Coding .
Conclusion
In this article, we discussed the Java naming conventions to be followed for consistent writing of code which makes the code more readable and maintainable.
Naming conventions are probably the first best practice to follow while writing clean code in any programming language.
Related posts
Naming Conventions in Java
A programmer is always said to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way out to read the code. At a smaller level, this seems meaningless but think of the industrial level where it becomes necessary to write clean codes in order to save time for which there are certain rules been laid of which one of the factors is to name the keyword right which is termed as a naming convention in Java.
For example when you are using a variable name depicting displacement then it should be named as “displace” or similar likewise not likely x, d which becomes complex as the code widens up and decreases the readability aperture. Consider the below illustrations to get a better understanding which later on we will be discussing in detail.
Illustrations:
- Class: If you are naming any class then it should be a noun and so should be named as per the goal to be achieved in the program such as Add2Numbers, ReverseString, and so on not likely A1, Programming, etc. It should be specific pointing what exactly is there inside without glancing at the body of the class.
- Interface: If you are naming an interface, it should look like an adjective such as consider the existing ones: Runnable, Serializable, etc. Try to use ‘able’ at the end, yes it is said to try as there are no hard and fast bound rules as if we do consider an inbuilt interface such as ‘Remote’, it is not having ble at the end. Consider if you are supposed to create an interface to make read operation then it is suggested as per naming conventions in java to name a similar likely ‘Readable’ interface.
- Methods: Now if we do look closer a method is supposed to do something that it does contains in its body henceforth it should be a verb.
- Constants: As the name suggests it should look like as we read it looks like it is fixed for examples PI, MAX_INT, MIN_INT, etc as follows.
Naming Conventions in Java
In java, it is good practice to name class, variables, and methods name as what they are actually supposed to do instead of naming them randomly. Below are some naming conventions of the java programming language. They must be followed while developing software in java for good maintenance and readability of code. Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.
Camel’s case in java programming consists of compound words or phrases such that each word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital. Here in simpler terms, it means if there are two
- In package, everything is small even while we are combining two or more words in java
- In constants, we do use everything as uppercase and only ‘_’ character is used even if we are combining two or more words in java.
Type 1: Classes and Interfaces
- Class names should be nouns, in mixed cases with the first letter of each internal word capitalized. Interfaces names should also be capitalized just like class names.
- Use whole words and must avoid acronyms and abbreviations.
Classes: class Student < >class Integer <> class Scanner <>
Interfaces : Runnable Remote Serializable
Type 2: Methods
- Methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized.
public static void main(String [] args) <>
As the name suggests the method is supposed to be primarily method which indeed it is as main() method in java is the method from where the program begins its execution.
Type 3: Variables
Variable names should be short yet meaningful.
Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
- Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
- One-character variable names should be avoided except for temporary variables.
- Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
int[] marks; double double answer,
As the name suggests one stands for marks while the other for an answer be it of any e do not mind.
Type 4: Constant variables
- Should be all uppercase with words separated by underscores (“_”).
- There are various constants used in predefined classes like Float, Long, String etc.
Type 5: Packages
- The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.
- Subsequent components of the package name vary according to an organization’s own internal naming conventions.
As the name suggests in the first case we are trying to access the Scanner class from the java.util package and in other all classes(* standing for all) input-output classes making it so easy for another programmer to identify.
- For class and interfaces, the first letter has to be uppercase.
- For method , variable, package_name, and constants, the first letter has to be lowercase.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.