When writing Java code, one of the most important practices is adhering to proper naming conventions. Consistent naming conventions improve code readability, maintainability, and understanding across developers.
- Class Names: Class names should be written in PascalCase (also known as UpperCamelCase). This means the first letter of each word is capitalized with no spaces between words.
|
1 2 3 |
public class CustomerDetails { // Class code here } |
- Method Names: Method names should follow camelCase—starting with a lowercase letter and capitalizing each subsequent word.
|
1 2 3 |
public void calculateTotalAmount() { // Method code here } |
- Variable Names: Variable names should also follow camelCase, just like method names, but they represent data. Use descriptive names that reflect the purpose of the variable.
|
1 2 |
int customerAge = 25; String productName = "Laptop"; |
- Constants: Constants in Java are usually written in UPPERCASE with words separated by underscores (
_). Constants are typically defined using thefinalkeyword, indicating they cannot be changed once initialized.
|
1 2 |
public static final int MAX_USERS = 1000; public static final String APP_NAME = "MyJavaApp"; |
- Package Names: Package names should be written in lowercase letters, and when combining multiple words, separate them with dots (
.).
|
1 |
package com.myjavaproject.utility; |
- Interface Names: Interface names typically use PascalCase and should be descriptive. It’s a common practice to prefix interface names with an
I(although this is optional, it’s widely used in some coding standards).
|
1 2 3 |
public interface Vehicle { void drive(); } |
- Enum Names: Enum names should follow PascalCase and should be singular if referring to a single constant or plural if referring to a group of constants.
|
1 2 3 |
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } |
- Generic Types: Generic type parameters are usually written in single uppercase letters. The most common convention is using
Tfor a general type and other letters likeEfor elements,Kfor keys, andVfor values.
|
1 2 3 4 5 6 7 |
public class Box<T> { private T item; public T getItem() { return item; } } |
Summary
| Element | Convention | Example |
|---|---|---|
| Class Names | PascalCase | CustomerDetails |
| Method Names | camelCase | calculateTotalAmount() |
| Variable Names | camelCase | customerAge, productName |
| Constants | UPPERCASE | MAX_USERS, APP_NAME |
| Package Names | lowercase | com.myjavaproject.utility |
| Interface Names | PascalCase | Vehicle |
| Enum Names | PascalCase | Day, Month |
| Generic Types | Uppercase single letters | T, E, K, V |