Java Naming Conventions

Java uses CamelCase conventions as the general practice. Although, you can compile code even without following the naming conventions, it is good practice to adhere to these conventions as this increases the readability of your code. CamelCase defines certain ways in which methods, classes, variables, interfaces, packages, and constants should be named. The various conventions are as follows:

  1. Classes and Interfaces:
    All class names should start with a capital letter followed by small letters. Each internal word should also start with a capital letter. Normally nouns are preferred as class names. Interfaces also follow the same convention.

    Example:

    interface SportsTeams
    class Rugby implements SportsTeams

    interface Student
    class Aman implements Student

  2. Methods:
    Methods should always start with a lowercase letter but every internal word should start with a capital letter. As methods are essentially functions, we always prefer these to be verbs rather than nouns.

    Example:

    void getValue();
    void setValue(int a);
    void sum(int a, int b);

  3. Variables:
    Variable names should be as precise as possible and should indicate the use of that variable in the code. It will also be better not to use single character variable names except temporary or loop control variables.

    Example:

    int speed = 0;
    int height = 0;

  4. Constant Variables:
    Constant variable values remain unchanged throughout the scope of the program. Therefore, the convention follows naming them using all uppercase letters where each internal word is separated by ‘_’.

    Example:

    static final int MAX_HEIGHT = 7;

  5. Packages:
    All-lowercase ASCII letters are used to write the names of prefixes of unique packages. This should also correspond to one of top-level domains names such as gov, mil, net, org, etc. Subsequent components are separated by ‘.’ and named as per the organisation’s conventions.

    Examples:
    import java.io.*;
    import java.lang;
    import java.util.*;

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.