Programming





Java Constants with Naming Convention

Java Constants with Naming Convention


by Administrator | 27-Mar-2020
Java

Tags:  Naming Convention  Constants  Core Java

Share: 


Constants are a special type of variable whose values cannot be modified once they are initialized. final modifier is mandatory for defining a constant.

 Syntax

[modifier] final <dataType> <varName> = <value>;

[modifier] static final <dataType> <varName> = <value>;

Example

  • final Integer MAX_SEARCH_RESULTS = 20;
  • public static final String WEBSITE_NAME;

     WEBSITE_NAME= "prgrmmng.com"

Program

public class ConstantExample {
    final static double PI = 3.14;

    public static void main(String[] args) {

        System.out.println("PI: " + PI);

        final int SHOE_SIZE = 10;
        System.out.println("SHOE_SIZE: " + SHOE_SIZE);

        final int SHIRT_SIZE;
        SHIRT_SIZE = 40;
        System.out.println("SHIRT_SIZE: " + SHIRT_SIZE);
    }
}

Output

PI: 3.14
SHOE_SIZE: 10
SHIRT_SIZE: 40

Rules and Naming Convention for Constants:

  1. A constant must be initialized before using else it will result in compile time .
  2. We cannot modify a constant if it has been initialized once which will also result in compile time error. 
  3. It is not mandatory to initialize a final variable in the same statement. If we want we can initialize them at a different place in the program where we are going to use them.
  4. A constant is usually declared by using both static and final modifiers. static modifier prevents from creating multiple instances of the same constant value and final prevents all the objects of the same class to access the same value.

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.