How to declare constants in Java?

final keyword is used to declare constants.

final can be used to declare constants
1. which is a data member in a class.
2. in an interface
3. local within a method.

Declared constant can be primitive or non primitive data type


Below is an example

class Abc{
    public void show()
    {
        System.out.println("show() method in Abc class");
    }
}

interface Test{
    final int VAL = 45;
}

public class FinalKeywordDemo {
    final static float XYZ = 3.5f;
    final static Abc obj = new Abc();
    public static void main(String args[])
    {
        final int MAX_VALUE = 10;
        //final keyword is used to define constant values

        //obj = new Abc();//error, b'coz obj is final
        //MAX_VALUE = 20; //error, b'coz ABC is final
        //XYZ = 5.8f; //error

        System.out.println(MAX_VALUE+" "+XYZ+" "+Test.VAL);
    }
}


You may also like to read:
Purpose of final method
What is final class

One thought on “How to declare constants in Java?”

Leave a Reply