Programming





Identifiers in Java

Identifiers in Java


by Administrator | 25-Mar-2020
Java

Tags:    Java  Identifier  Naming Convention

Share: 


Identifiers are the name provided to the programming entities by the user. We can provide names to variables, methods, constants, custom types like class, interface, enum, annotation. For eg

class Student{
    public static void main(String[] args){
        int sNo;
        String studentName;                     
    }
}

In the above example Student, main, args, sNo, studentName are identifiers.

There are some rules which should be kept in mind when declaring an identifier:

  1. It can only contain alphabets (A-Z, a-z), digits (0-9), _ (underscore) or $ (dollar) symbol.
  2. It cannot start with a digit (0-9).
  3. It cannot contain any other character even space.
  4. Keywords cannot be used as a user-defined identifier.
  5. Following are not a reserved keyword in java but cannot be used as a user-defined identifier: true, false, null
  6. Java is case sensitive so the identifiers with the different cases will not be treated the same.

Valid Identifiers:

  • i
  • Number
  • variable
  • NUMBER
  • _variable
  • $number
  • _50cent
  • This_is_a_very_long_name_what_are_you_gonna_do_about_it

Invalid Identifiers:

  • 50cent // Begins with a number
  • My Number // Contains a space
  • a+b // plus sign is not an alphanumeric character
  • Mc’rib // Apostrophe is not an alphanumeric character
  • something_&_something // ampersand is not an alphanumeric character

Naming Conventions

We should keep these things in mind while defining identifiers. These are not a compulsion and will not result in a compile-time error. These are more like suggestions and everyone in the industry follows it:

a. Naming A Custom Type

  1. The name should start with an uppercase character.
  2. The remaining characters should be in lowercase if the identifier consists of one word.
  3. If the name contains more than one word then the first character of every word should be in uppercase and the remaining characters should be in lowercase.

Examples: Executable, Student, BatchTiming, CourceDetails, UserInFormation etc.

b. Naming a Method or Object or Variable

  1. The name should start with a lowercase letter.
  2. If it contains multiple words then from second word onwards the first character should be uppercase and the remaining should be in lowercase. For e.g. email, employeePhone, branchName, getCourceDetailsByCourceId(), getName(), isValid() etc.

c. Naming a Constant

  1. All the characters should be uppercase.
  2. If the name contains multiple words then we need to use _ (underscore) symbol as a separator between two words. For eg MIN_VALUE, FULL_COURCE_FEE, etc.

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.