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
Java
1// ❌ BAD - No conventions 2public class data { 3 int X; 4 String NAME; 5 6 void DoSomething() { 7 int temp_value = 10; 8 } 9} 10 11// ✅ GOOD - Follows conventions 12public class DataProcessor { 13 private int count; 14 private String userName; 15 16 public void processData() { 17 int temporaryValue = 10; 18 } 19}

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
Java
1// ✅ CORRECT Examples 2public class Student { } 3public class BankAccount { } 4public class UserProfileManager { } 5public class HttpRequestHandler { } 6public class DatabaseConnection { } 7public class OrderProcessor { } 8 9// ❌ WRONG Examples 10public class student { } // Should start with capital 11public class STUDENT { } // Don't use all caps 12public class Student_Info { } // Don't use underscores 13public class StudentClass { } // Don't add "Class" suffix 14public class doProcessing { } // Don't use verbs 15public class Data { } // Too vague

Specific Types of Classes

Abstract Classes:

Java
1// Use descriptive nouns, often with "Base" or generic names 2public abstract class Animal { } 3public abstract class Shape { } 4public abstract class BaseRepository { } 5public abstract class AbstractDataProcessor { }

Exception Classes:

Java
1// Always end with "Exception" 2public class UserNotFoundException extends Exception { } 3public class InvalidInputException extends RuntimeException { } 4public class DatabaseConnectionException extends Exception { } 5public class PaymentProcessingException extends Exception { }

Utility Classes:

Java
1// Often plural nouns or end with "Utils" or "Helper" 2public class StringUtils { } 3public class MathHelper { } 4public class DateFormatter { } 5public class Collections { }

Test Classes:

Java
1// Name of class being tested + "Test" 2public class StudentTest { } 3public class BankAccountTest { } 4public 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
Java
1// ✅ CORRECT Examples - Adjectives 2public interface Runnable { } 3public interface Comparable { } 4public interface Serializable { } 5public interface Cloneable { } 6public interface Readable { } 7public interface Closeable { } 8 9// ✅ CORRECT Examples - Nouns 10public interface List { } 11public interface Map { } 12public interface Connection { } 13public interface Observer { } 14public interface Listener { } 15 16// ❌ WRONG Examples 17public interface IStudent { } // Don't use "I" prefix 18public interface StudentInterface { } // Don't add "Interface" 19public interface student { } // Should start with capital

Interface vs Class Naming

Java
1// Interface: Capability or contract 2public interface Drawable { 3 void draw(); 4} 5 6// Class: Implementation 7public class Circle implements Drawable { 8 @Override 9 public void draw() { 10 // Implementation 11 } 12} 13 14// Another pattern 15public interface PaymentProcessor { 16 void processPayment(double amount); 17} 18 19public class StripePaymentProcessor implements PaymentProcessor { 20 @Override 21 public void processPayment(double amount) { 22 // Stripe-specific implementation 23 } 24}

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
Java
1// ✅ CORRECT Examples 2public void calculateTotal() { } 3public int getUserAge() { } 4public void setUserName(String name) { } 5public boolean isValid() { } 6public boolean hasPermission() { } 7public void processOrder() { } 8public String formatDate() { } 9 10// ❌ WRONG Examples 11public void CalculateTotal() { } // Don't start with capital 12public void calculate_total() { } // Don't use underscores 13public void calc() { } // Don't abbreviate unnecessarily 14public void Total() { } // Use verbs, not nouns 15public void CALCULATE() { } // Don't use all caps

Method Naming Patterns

Getters (Accessors):

Java
1public class Student { 2 private String name; 3 private int age; 4 private boolean active; 5 6 // Getters start with "get" 7 public String getName() { 8 return name; 9 } 10 11 public int getAge() { 12 return age; 13 } 14 15 // Boolean getters can start with "is" or "has" 16 public boolean isActive() { 17 return active; 18 } 19}

Setters (Mutators):

Java
1public class Student { 2 private String name; 3 private int age; 4 5 // Setters start with "set" 6 public void setName(String name) { 7 this.name = name; 8 } 9 10 public void setAge(int age) { 11 this.age = age; 12 } 13}

Boolean Methods:

Java
1public class Validator { 2 // Use "is", "has", "can", "should" 3 public boolean isValid() { return true; } 4 public boolean isEmpty() { return false; } 5 public boolean hasPermission() { return true; } 6 public boolean canEdit() { return true; } 7 public boolean shouldUpdate() { return false; } 8 9 // ❌ WRONG 10 public boolean valid() { } // Missing "is" 11 public boolean checkValid() { } // Don't use "check" 12}

Action Methods:

Java
1public class UserService { 2 // Start with strong verbs 3 public void createUser() { } 4 public void deleteUser() { } 5 public void updateUser() { } 6 public void saveUser() { } 7 public void loadUser() { } 8 public void sendEmail() { } 9 public void processPayment() { } 10 public void validateInput() { } 11 public void calculateTotal() { } 12}

Conversion Methods:

Java
1public class Converter { 2 // Use "to" prefix for conversions 3 public String toString() { return ""; } 4 public int toInt() { return 0; } 5 public double toDouble() { return 0.0; } 6 public List<String> toList() { return null; } 7}

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)
Java
1// ✅ CORRECT Examples 2int studentAge; 3String firstName; 4double accountBalance; 5boolean isActive; 6List<String> userNames; 7Map<Integer, User> userMap; 8 9// ❌ WRONG Examples 10int StudentAge; // Don't start with capital 11int student_age; // Don't use underscores 12int age1; // Don't use numbers without context 13int a; // Too short (except in loops) 14int temp; // Too vague

Specific Variable Types

Instance Variables (Fields):

Java
1public class BankAccount { 2 // Private fields 3 private String accountNumber; 4 private double balance; 5 private String ownerName; 6 private boolean isActive; 7 8 // No "m" prefix or underscore suffix 9 // ❌ WRONG 10 private String m_accountNumber; // Don't use Hungarian notation 11 private String accountNumber_; // Don't use underscore suffix 12}

Local Variables:

Java
1public void processOrder() { 2 // Use descriptive names 3 int totalItems = 0; 4 double totalPrice = 0.0; 5 String customerName = "John"; 6 7 // Loop variables can be short 8 for (int i = 0; i < 10; i++) { 9 // "i", "j", "k" are acceptable for simple loops 10 } 11 12 // But for complex loops, use descriptive names 13 for (int orderIndex = 0; orderIndex < orders.size(); orderIndex++) { 14 Order currentOrder = orders.get(orderIndex); 15 } 16}

Boolean Variables:

Java
1public class User { 2 // Use "is", "has", "can", "should" 3 private boolean isActive; 4 private boolean hasPermission; 5 private boolean canEdit; 6 private boolean shouldNotify; 7 8 // ❌ WRONG 9 private boolean active; // Missing "is" 10 private boolean permission; // Missing "has" 11}

Collection Variables:

Java
1public class School { 2 // Use plural names for collections 3 private List<Student> students; // ✅ Plural 4 private Set<String> courseNames; // ✅ Plural 5 private Map<Integer, User> userMap; // ✅ "Map" suffix 6 7 // ❌ WRONG 8 private List<Student> studentList; // Redundant "List" 9 private List<Student> student; // Should be plural 10}

5. Constant Naming Conventions

Rules for Constants

Convention: ALL_UPPERCASE_WITH_UNDERSCORES

  • All letters uppercase
  • Words separated by underscores
  • Must be static final
Java
1public class Constants { 2 // ✅ CORRECT Examples 3 public static final int MAX_SIZE = 100; 4 public static final String DEFAULT_NAME = "Unknown"; 5 public static final double PI = 3.14159; 6 public static final int TIMEOUT_SECONDS = 30; 7 public static final String DATABASE_URL = "localhost"; 8 9 // ❌ WRONG Examples 10 public static final int maxSize = 100; // Should be uppercase 11 public static final int MaxSize = 100; // Should be uppercase 12 public static final int max_Size = 100; // Inconsistent 13}

Constant Categories

Java
1public class ApplicationConstants { 2 // Configuration constants 3 public static final int DEFAULT_TIMEOUT = 5000; 4 public static final String API_BASE_URL = "https://api.example.com"; 5 public static final int MAX_RETRY_ATTEMPTS = 3; 6 7 // Status codes 8 public static final int STATUS_SUCCESS = 200; 9 public static final int STATUS_NOT_FOUND = 404; 10 public static final int STATUS_ERROR = 500; 11 12 // Mathematical constants 13 public static final double PI = 3.14159; 14 public static final double E = 2.71828; 15 16 // Color constants 17 public static final String COLOR_RED = "#FF0000"; 18 public static final String COLOR_GREEN = "#00FF00"; 19 public static final String COLOR_BLUE = "#0000FF"; 20}

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
Java
1// ✅ CORRECT Examples 2package com.example.myapp; 3package com.google.common.collect; 4package org.apache.commons.lang; 5package io.github.username.project; 6package com.company.product.module; 7 8// ❌ WRONG Examples 9package com.Example.MyApp; // Don't use capitals 10package com.example.my_app; // Don't use underscores 11package com.example.MyApp; // Don't use PascalCase 12package Example; // Too short/vague

Package Structure

Java
1// Typical package structure 2com.company.project 3├── model // Data models/entities 4├── repository // Database access 5├── service // Business logic 6├── controller // API endpoints 7├── util // Utility classes 8└── exception // Custom exceptions 9 10// Example: 11package com.example.ecommerce.model; 12package com.example.ecommerce.repository; 13package com.example.ecommerce.service; 14package com.example.ecommerce.controller; 15package com.example.ecommerce.util; 16package com.example.ecommerce.exception;

7. Enum Naming Conventions

Rules for Enums

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

Java
1// ✅ CORRECT Examples 2public enum DayOfWeek { 3 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY 4} 5 6public enum OrderStatus { 7 PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED 8} 9 10public enum UserRole { 11 ADMIN, MANAGER, EMPLOYEE, GUEST 12} 13 14// ❌ WRONG Examples 15public enum dayOfWeek { // Should be PascalCase 16 Monday, Tuesday, Wednesday // Should be ALL_CAPS 17} 18 19public enum OrderStatus { 20 pending, processing // Should be ALL_CAPS 21}

Enum with Methods

Java
1public enum Season { 2 SPRING("March - May"), 3 SUMMER("June - August"), 4 FALL("September - November"), 5 WINTER("December - February"); 6 7 private final String months; 8 9 Season(String months) { 10 this.months = months; 11 } 12 13 public String getMonths() { 14 return months; 15 } 16}

8. Generic Type Parameter Conventions

Rules for Type Parameters

Convention: Single uppercase letter or short name in PascalCase

Java
1// ✅ CORRECT - Single letters 2public class Box<T> { } // T = Type 3public class Pair<K, V> { } // K = Key, V = Value 4public class Result<T, E> { } // T = Type, E = Error 5 6// ✅ CORRECT - Descriptive names 7public class Repository<Entity> { } 8public class Converter<Input, Output> { } 9public class Cache<KeyType, ValueType> { } 10 11// Common conventions: 12// T = Type 13// E = Element 14// K = Key 15// V = Value 16// N = Number

Generic Type Examples

Java
1// Standard Java generics 2public class ArrayList<E> { 3 // E represents Element type 4} 5 6public interface Map<K, V> { 7 // K = Key type, V = Value type 8} 9 10// Custom generics 11public class DataProcessor<T> { 12 public T process(T input) { 13 return input; 14 } 15} 16 17public class Pair<K, V> { 18 private K key; 19 private V value; 20 21 public Pair(K key, V value) { 22 this.key = key; 23 this.value = value; 24 } 25}

Complete Examples

Example 1: User Management System

Java
1// Package declaration 2package com.company.usermanagement.model; 3 4// Imports 5import java.time.LocalDateTime; 6import java.util.List; 7 8/** 9 * Represents a user in the system. 10 */ 11public class User { 12 // Constants 13 public static final int MIN_PASSWORD_LENGTH = 8; 14 public static final int MAX_USERNAME_LENGTH = 50; 15 16 // Instance variables 17 private int userId; 18 private String userName; 19 private String email; 20 private String password; 21 private boolean isActive; 22 private boolean hasAdminRights; 23 private LocalDateTime createdAt; 24 private LocalDateTime lastLoginTime; 25 26 // Constructor 27 public User(String userName, String email, String password) { 28 this.userName = userName; 29 this.email = email; 30 this.password = password; 31 this.isActive = true; 32 this.hasAdminRights = false; 33 this.createdAt = LocalDateTime.now(); 34 } 35 36 // Getters 37 public int getUserId() { 38 return userId; 39 } 40 41 public String getUserName() { 42 return userName; 43 } 44 45 public String getEmail() { 46 return email; 47 } 48 49 public boolean isActive() { 50 return isActive; 51 } 52 53 public boolean hasAdminRights() { 54 return hasAdminRights; 55 } 56 57 // Setters 58 public void setUserName(String userName) { 59 this.userName = userName; 60 } 61 62 public void setEmail(String email) { 63 this.email = email; 64 } 65 66 public void setActive(boolean active) { 67 this.isActive = active; 68 } 69 70 // Business methods 71 public void changePassword(String oldPassword, String newPassword) { 72 if (this.password.equals(oldPassword)) { 73 if (newPassword.length() >= MIN_PASSWORD_LENGTH) { 74 this.password = newPassword; 75 } 76 } 77 } 78 79 public void updateLastLoginTime() { 80 this.lastLoginTime = LocalDateTime.now(); 81 } 82 83 public boolean canAccessAdminPanel() { 84 return isActive && hasAdminRights; 85 } 86}

Example 2: Service Layer

Java
1package com.company.usermanagement.service; 2 3import com.company.usermanagement.model.User; 4import com.company.usermanagement.exception.UserNotFoundException; 5import java.util.List; 6 7/** 8 * Service for managing user operations. 9 */ 10public class UserService { 11 // Constants 12 private static final int MAX_LOGIN_ATTEMPTS = 3; 13 14 // Dependencies 15 private UserRepository userRepository; 16 private EmailService emailService; 17 18 // Constructor 19 public UserService(UserRepository userRepository, EmailService emailService) { 20 this.userRepository = userRepository; 21 this.emailService = emailService; 22 } 23 24 // Public methods 25 public User createUser(String userName, String email, String password) { 26 User newUser = new User(userName, email, password); 27 userRepository.save(newUser); 28 emailService.sendWelcomeEmail(email); 29 return newUser; 30 } 31 32 public User getUserById(int userId) throws UserNotFoundException { 33 User user = userRepository.findById(userId); 34 if (user == null) { 35 throw new UserNotFoundException("User not found with ID: " + userId); 36 } 37 return user; 38 } 39 40 public List<User> getAllActiveUsers() { 41 return userRepository.findByActive(true); 42 } 43 44 public void deactivateUser(int userId) { 45 User user = getUserById(userId); 46 user.setActive(false); 47 userRepository.update(user); 48 } 49 50 public boolean validateCredentials(String userName, String password) { 51 User user = userRepository.findByUserName(userName); 52 return user != null && user.getPassword().equals(password); 53 } 54 55 // Private helper methods 56 private void logUserActivity(int userId, String activity) { 57 // Implementation 58 } 59 60 private boolean isValidEmail(String email) { 61 return email.contains("@") && email.contains("."); 62 } 63}

Common Mistakes to Avoid

Mistake 1: Inconsistent Naming

Java
1// ❌ WRONG - Inconsistent style 2public class user_manager { 3 int UserAge; 4 String user_name; 5 boolean ISACTIVE; 6 7 void Get_User() { } 8 void setUserName() { } 9} 10 11// ✅ CORRECT - Consistent style 12public class UserManager { 13 private int userAge; 14 private String userName; 15 private boolean isActive; 16 17 public User getUser() { } 18 public void setUserName(String userName) { } 19}

Mistake 2: Abbreviations

Java
1// ❌ WRONG - Unclear abbreviations 2int cnt; 3String usrNm; 4boolean flg; 5void procData() { } 6 7// ✅ CORRECT - Full words 8int count; 9String userName; 10boolean isValid; 11void processData() { }

Mistake 3: Hungarian Notation

Java
1// ❌ WRONG - Hungarian notation (outdated) 2String strName; 3int iCount; 4boolean bIsValid; 5 6// ✅ CORRECT - Modern Java conventions 7String name; 8int count; 9boolean isValid;

Mistake 4: Redundant Names

Java
1// ❌ WRONG - Redundant information 2public class UserClass { } 3public interface IUserService { } 4List<User> userList; 5public void getUserUser() { } 6 7// ✅ CORRECT - Concise and clear 8public class User { } 9public interface UserService { } 10List<User> users; 11public void getUser() { }

Mistake 5: Too Short or Too Long

Java
1// ❌ WRONG - Too short 2int x; 3String s; 4void p() { } 5 6// ❌ WRONG - Too long 7int numberOfStudentsCurrentlyEnrolledInTheClass; 8void calculateTheTotalPriceOfAllItemsInTheShoppingCart() { } 9 10// ✅ CORRECT - Just right 11int studentCount; 12void 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

What's Next?

Now that you understand naming conventions:

  1. Code Style - Formatting and organization
  2. Documentation - JavaDoc and comments
  3. Best Practices - Writing clean code

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

Java Naming Conventions | DevStackFlow