Java Tutorial
🔍

Java Naming Conventions

Java Naming Conventions

Naming conventions are standardized rules for naming classes, methods, variables, and other identifiers in Java. Following these conventions makes your code readable, maintainable, and professional.

Goal: Master Java naming conventions used by professional developers and followed by major companies like Google, Oracle, and Microsoft.

Key Insight: Good naming is not just about following rules—it's about making your code self-documenting. A well-named variable explains its purpose without needing comments.

Why Naming Conventions Matter

Benefits:

  • ›Readability: Code is easier to understand
  • ›Maintainability: Easier to modify and debug
  • ›Collaboration: Teams can work together seamlessly
  • ›Professionalism: Shows you're a serious developer
// ❌ BAD - No conventions public class data { int X; String NAME; void DoSomething() { int temp_value = 10; } } // ✅ GOOD - Follows conventions public class DataProcessor { private int count; private String userName; public void processData() { int temporaryValue = 10; } }

1. Class Naming Conventions

Rules for Classes

Convention: PascalCase (UpperCamelCase)

  • ›Start with uppercase letter
  • ›Capitalize first letter of each word
  • ›Use nouns or noun phrases
  • ›Should be descriptive and specific
// ✅ CORRECT Examples public class Student { } public class BankAccount { } public class UserProfileManager { } public class HttpRequestHandler { } public class DatabaseConnection { } public class OrderProcessor { } // ❌ WRONG Examples public class student { } // Should start with capital public class STUDENT { } // Don't use all caps public class Student_Info { } // Don't use underscores public class StudentClass { } // Don't add "Class" suffix public class doProcessing { } // Don't use verbs public class Data { } // Too vague

Specific Types of Classes

Abstract Classes:

// Use descriptive nouns, often with "Base" or generic names public abstract class Animal { } public abstract class Shape { } public abstract class BaseRepository { } public abstract class AbstractDataProcessor { }

Exception Classes:

// Always end with "Exception" public class UserNotFoundException extends Exception { } public class InvalidInputException extends RuntimeException { } public class DatabaseConnectionException extends Exception { } public class PaymentProcessingException extends Exception { }

Utility Classes:

// Often plural nouns or end with "Utils" or "Helper" public class StringUtils { } public class MathHelper { } public class DateFormatter { } public class Collections { }

Test Classes:

// Name of class being tested + "Test" public class StudentTest { } public class BankAccountTest { } public class UserServiceTest { }

2. Interface Naming Conventions

Rules for Interfaces

Convention: PascalCase (same as classes)

  • ›Use adjectives (often ending in -able, -ible)
  • ›Or use nouns representing capabilities
// ✅ CORRECT Examples - Adjectives public interface Runnable { } public interface Comparable { } public interface Serializable { } public interface Cloneable { } public interface Readable { } public interface Closeable { } // ✅ CORRECT Examples - Nouns public interface List { } public interface Map { } public interface Connection { } public interface Observer { } public interface Listener { } // ❌ WRONG Examples public interface IStudent { } // Don't use "I" prefix public interface StudentInterface { } // Don't add "Interface" public interface student { } // Should start with capital

Interface vs Class Naming

// Interface: Capability or contract public interface Drawable { void draw(); } // Class: Implementation public class Circle implements Drawable { @Override public void draw() { // Implementation } } // Another pattern public interface PaymentProcessor { void processPayment(double amount); } public class StripePaymentProcessor implements PaymentProcessor { @Override public void processPayment(double amount) { // Stripe-specific implementation } }

3. Method Naming Conventions

Rules for Methods

Convention: camelCase (lowerCamelCase)

  • ›Start with lowercase letter
  • ›Capitalize first letter of subsequent words
  • ›Use verbs or verb phrases
  • ›Should describe what the method does
// ✅ CORRECT Examples public void calculateTotal() { } public int getUserAge() { } public void setUserName(String name) { } public boolean isValid() { } public boolean hasPermission() { } public void processOrder() { } public String formatDate() { } // ❌ WRONG Examples public void CalculateTotal() { } // Don't start with capital public void calculate_total() { } // Don't use underscores public void calc() { } // Don't abbreviate unnecessarily public void Total() { } // Use verbs, not nouns public void CALCULATE() { } // Don't use all caps

Method Naming Patterns

Getters (Accessors):

public class Student { private String name; private int age; private boolean active; // Getters start with "get" public String getName() { return name; } public int getAge() { return age; } // Boolean getters can start with "is" or "has" public boolean isActive() { return active; } }

Setters (Mutators):

public class Student { private String name; private int age; // Setters start with "set" public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }

Boolean Methods:

public class Validator { // Use "is", "has", "can", "should" public boolean isValid() { return true; } public boolean isEmpty() { return false; } public boolean hasPermission() { return true; } public boolean canEdit() { return true; } public boolean shouldUpdate() { return false; } // ❌ WRONG public boolean valid() { } // Missing "is" public boolean checkValid() { } // Don't use "check" }

Action Methods:

public class UserService { // Start with strong verbs public void createUser() { } public void deleteUser() { } public void updateUser() { } public void saveUser() { } public void loadUser() { } public void sendEmail() { } public void processPayment() { } public void validateInput() { } public void calculateTotal() { } }

Conversion Methods:

public class Converter { // Use "to" prefix for conversions public String toString() { return ""; } public int toInt() { return 0; } public double toDouble() { return 0.0; } public List<String> toList() { return null; } }

4. Variable Naming Conventions

Rules for Variables

Convention: camelCase (lowerCamelCase)

  • ›Start with lowercase letter
  • ›Capitalize first letter of subsequent words
  • ›Use meaningful, descriptive names
  • ›Avoid single letters (except for loops)
// ✅ CORRECT Examples int studentAge; String firstName; double accountBalance; boolean isActive; List<String> userNames; Map<Integer, User> userMap; // ❌ WRONG Examples int StudentAge; // Don't start with capital int student_age; // Don't use underscores int age1; // Don't use numbers without context int a; // Too short (except in loops) int temp; // Too vague

Specific Variable Types

Instance Variables (Fields):

public class BankAccount { // Private fields private String accountNumber; private double balance; private String ownerName; private boolean isActive; // No "m" prefix or underscore suffix // ❌ WRONG private String m_accountNumber; // Don't use Hungarian notation private String accountNumber_; // Don't use underscore suffix }

Local Variables:

public void processOrder() { // Use descriptive names int totalItems = 0; double totalPrice = 0.0; String customerName = "John"; // Loop variables can be short for (int i = 0; i < 10; i++) { // "i", "j", "k" are acceptable for simple loops } // But for complex loops, use descriptive names for (int orderIndex = 0; orderIndex < orders.size(); orderIndex++) { Order currentOrder = orders.get(orderIndex); } }

Boolean Variables:

public class User { // Use "is", "has", "can", "should" private boolean isActive; private boolean hasPermission; private boolean canEdit; private boolean shouldNotify; // ❌ WRONG private boolean active; // Missing "is" private boolean permission; // Missing "has" }

Collection Variables:

public class School { // Use plural names for collections private List<Student> students; // ✅ Plural private Set<String> courseNames; // ✅ Plural private Map<Integer, User> userMap; // ✅ "Map" suffix // ❌ WRONG private List<Student> studentList; // Redundant "List" private List<Student> student; // Should be plural }

5. Constant Naming Conventions

Rules for Constants

Convention: ALL_UPPERCASE_WITH_UNDERSCORES

  • ›All letters uppercase
  • ›Words separated by underscores
  • ›Must be static final
public class Constants { // ✅ CORRECT Examples public static final int MAX_SIZE = 100; public static final String DEFAULT_NAME = "Unknown"; public static final double PI = 3.14159; public static final int TIMEOUT_SECONDS = 30; public static final String DATABASE_URL = "localhost"; // ❌ WRONG Examples public static final int maxSize = 100; // Should be uppercase public static final int MaxSize = 100; // Should be uppercase public static final int max_Size = 100; // Inconsistent }

Constant Categories

public class ApplicationConstants { // Configuration constants public static final int DEFAULT_TIMEOUT = 5000; public static final String API_BASE_URL = "https://api.example.com"; public static final int MAX_RETRY_ATTEMPTS = 3; // Status codes public static final int STATUS_SUCCESS = 200; public static final int STATUS_NOT_FOUND = 404; public static final int STATUS_ERROR = 500; // Mathematical constants public static final double PI = 3.14159; public static final double E = 2.71828; // Color constants public static final String COLOR_RED = "#FF0000"; public static final String COLOR_GREEN = "#00FF00"; public static final String COLOR_BLUE = "#0000FF"; }

6. Package Naming Conventions

Rules for Packages

Convention: all lowercase, separated by dots

  • ›Use your reversed domain name
  • ›All lowercase letters
  • ›No underscores or special characters
// ✅ CORRECT Examples package com.example.myapp; package com.google.common.collect; package org.apache.commons.lang; package io.github.username.project; package com.company.product.module; // ❌ WRONG Examples package com.Example.MyApp; // Don't use capitals package com.example.my_app; // Don't use underscores package com.example.MyApp; // Don't use PascalCase package Example; // Too short/vague

Package Structure

// Typical package structure com.company.project ├── model // Data models/entities ├── repository // Database access ├── service // Business logic ├── controller // API endpoints ├── util // Utility classes └── exception // Custom exceptions // Example: package com.example.ecommerce.model; package com.example.ecommerce.repository; package com.example.ecommerce.service; package com.example.ecommerce.controller; package com.example.ecommerce.util; package com.example.ecommerce.exception;

7. Enum Naming Conventions

Rules for Enums

Enum Type: PascalCase (like classes) Enum Values: ALL_UPPERCASE_WITH_UNDERSCORES (like constants)

// ✅ CORRECT Examples public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } public enum OrderStatus { PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED } public enum UserRole { ADMIN, MANAGER, EMPLOYEE, GUEST } // ❌ WRONG Examples public enum dayOfWeek { // Should be PascalCase Monday, Tuesday, Wednesday // Should be ALL_CAPS } public enum OrderStatus { pending, processing // Should be ALL_CAPS }

Enum with Methods

public enum Season { SPRING("March - May"), SUMMER("June - August"), FALL("September - November"), WINTER("December - February"); private final String months; Season(String months) { this.months = months; } public String getMonths() { return months; } }

8. Generic Type Parameter Conventions

Rules for Type Parameters

Convention: Single uppercase letter or short name in PascalCase

// ✅ CORRECT - Single letters public class Box<T> { } // T = Type public class Pair<K, V> { } // K = Key, V = Value public class Result<T, E> { } // T = Type, E = Error // ✅ CORRECT - Descriptive names public class Repository<Entity> { } public class Converter<Input, Output> { } public class Cache<KeyType, ValueType> { } // Common conventions: // T = Type // E = Element // K = Key // V = Value // N = Number

Generic Type Examples

// Standard Java generics public class ArrayList<E> { // E represents Element type } public interface Map<K, V> { // K = Key type, V = Value type } // Custom generics public class DataProcessor<T> { public T process(T input) { return input; } } public class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } }

Complete Examples

Example 1: User Management System

// Package declaration package com.company.usermanagement.model; // Imports import java.time.LocalDateTime; import java.util.List; /** * Represents a user in the system. */ public class User { // Constants public static final int MIN_PASSWORD_LENGTH = 8; public static final int MAX_USERNAME_LENGTH = 50; // Instance variables private int userId; private String userName; private String email; private String password; private boolean isActive; private boolean hasAdminRights; private LocalDateTime createdAt; private LocalDateTime lastLoginTime; // Constructor public User(String userName, String email, String password) { this.userName = userName; this.email = email; this.password = password; this.isActive = true; this.hasAdminRights = false; this.createdAt = LocalDateTime.now(); } // Getters public int getUserId() { return userId; } public String getUserName() { return userName; } public String getEmail() { return email; } public boolean isActive() { return isActive; } public boolean hasAdminRights() { return hasAdminRights; } // Setters public void setUserName(String userName) { this.userName = userName; } public void setEmail(String email) { this.email = email; } public void setActive(boolean active) { this.isActive = active; } // Business methods public void changePassword(String oldPassword, String newPassword) { if (this.password.equals(oldPassword)) { if (newPassword.length() >= MIN_PASSWORD_LENGTH) { this.password = newPassword; } } } public void updateLastLoginTime() { this.lastLoginTime = LocalDateTime.now(); } public boolean canAccessAdminPanel() { return isActive && hasAdminRights; } }

Example 2: Service Layer

package com.company.usermanagement.service; import com.company.usermanagement.model.User; import com.company.usermanagement.exception.UserNotFoundException; import java.util.List; /** * Service for managing user operations. */ public class UserService { // Constants private static final int MAX_LOGIN_ATTEMPTS = 3; // Dependencies private UserRepository userRepository; private EmailService emailService; // Constructor public UserService(UserRepository userRepository, EmailService emailService) { this.userRepository = userRepository; this.emailService = emailService; } // Public methods public User createUser(String userName, String email, String password) { User newUser = new User(userName, email, password); userRepository.save(newUser); emailService.sendWelcomeEmail(email); return newUser; } public User getUserById(int userId) throws UserNotFoundException { User user = userRepository.findById(userId); if (user == null) { throw new UserNotFoundException("User not found with ID: " + userId); } return user; } public List<User> getAllActiveUsers() { return userRepository.findByActive(true); } public void deactivateUser(int userId) { User user = getUserById(userId); user.setActive(false); userRepository.update(user); } public boolean validateCredentials(String userName, String password) { User user = userRepository.findByUserName(userName); return user != null && user.getPassword().equals(password); } // Private helper methods private void logUserActivity(int userId, String activity) { // Implementation } private boolean isValidEmail(String email) { return email.contains("@") && email.contains("."); } }

Common Mistakes to Avoid

Mistake 1: Inconsistent Naming

// ❌ WRONG - Inconsistent style public class user_manager { int UserAge; String user_name; boolean ISACTIVE; void Get_User() { } void setUserName() { } } // ✅ CORRECT - Consistent style public class UserManager { private int userAge; private String userName; private boolean isActive; public User getUser() { } public void setUserName(String userName) { } }

Mistake 2: Abbreviations

// ❌ WRONG - Unclear abbreviations int cnt; String usrNm; boolean flg; void procData() { } // ✅ CORRECT - Full words int count; String userName; boolean isValid; void processData() { }

Mistake 3: Hungarian Notation

// ❌ WRONG - Hungarian notation (outdated) String strName; int iCount; boolean bIsValid; // ✅ CORRECT - Modern Java conventions String name; int count; boolean isValid;

Mistake 4: Redundant Names

// ❌ WRONG - Redundant information public class UserClass { } public interface IUserService { } List<User> userList; public void getUserUser() { } // ✅ CORRECT - Concise and clear public class User { } public interface UserService { } List<User> users; public void getUser() { }

Mistake 5: Too Short or Too Long

// ❌ WRONG - Too short int x; String s; void p() { } // ❌ WRONG - Too long int numberOfStudentsCurrentlyEnrolledInTheClass; void calculateTheTotalPriceOfAllItemsInTheShoppingCart() { } // ✅ CORRECT - Just right int studentCount; void calculateTotalPrice() { }

Best Practices Summary

Naming Convention Cheat Sheet:

Classes:

  • ›PascalCase: StudentManager, DatabaseConnection
  • ›Use nouns: Order, Payment, UserProfile
  • ›Be specific: HttpRequestHandler not Handler

Interfaces:

  • ›PascalCase: Runnable, Comparable
  • ›Use adjectives (-able, -ible): Drawable, Serializable
  • ›Or nouns: List, Map, Connection

Methods:

  • ›camelCase: calculateTotal(), getUserName()
  • ›Use verbs: create(), update(), delete()
  • ›Getters: getName(), isActive()
  • ›Setters: setName(), setActive()
  • ›Boolean: isValid(), hasPermission(), canEdit()

Variables:

  • ›camelCase: studentAge, firstName, isActive
  • ›Descriptive: totalPrice not tp
  • ›Boolean: isActive, hasPermission
  • ›Collections: plural names (students, orders)

Constants:

  • ›ALL_UPPERCASE: MAX_SIZE, DEFAULT_TIMEOUT
  • ›Underscores between words: MIN_PASSWORD_LENGTH
  • ›Always static final

Packages:

  • ›all lowercase: com.example.project
  • ›Reverse domain: com.company.product.module
  • ›No underscores: userservice not user_service

Enums:

  • ›Type: PascalCase (DayOfWeek, OrderStatus)
  • ›Values: ALL_UPPERCASE (MONDAY, PENDING)

Type Parameters:

  • ›Single letter: T, E, K, V
  • ›Or PascalCase: Entity, KeyType

Remember:

  • ›Be consistent throughout your codebase
  • ›Prioritize clarity over brevity
  • ›Follow team/project conventions
  • ›Make names self-documenting

Congratulations! You now know professional Java naming conventions used in industry!

What to Read Next