[java] How to declare a constant in Java

We always write:

public static final int A = 0;  

Question:

  1. Is static final the only way to declare a constant in a class?
  2. If I write public final int A = 0; instead, is A still a constant or just an instance field?
  3. What is an instance variable? What's the difference between an instance variable and an instance field?

This question is related to java constants

The answer is


final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.


Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

Have a look on this Java tutorial for better understanding ,