Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between constant variables and final variables in java?

Please help me understand the difference between constant variables and final variables in Java. I am a bit confused with it.

like image 881
Swaram Jagtap Avatar asked May 30 '15 11:05

Swaram Jagtap


People also ask

What is constant and final in Java?

Constant is the concept, the property of the variable. final is the java keyword to declare a constant variable. As other people pointed out, from a semantic/linguistic point of view the expression constant variable is an oxymoron and, as such, we could argue about its correctness.

What is difference between const and final?

The only difference between the final and const keyword is that final is a runtime-constant, which in turn means that its value can be assigned at runtime instead of the compile-time that we had for the const keyword.

What is the difference between static and final variable in Java?

The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.

What is final variable in Java?

In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes. Once any entity (variable, method or class) is declared final , it can be assigned only once. That is, the final variable cannot be reinitialized with another value.


1 Answers

Constant is the concept, the property of the variable.

final is the java keyword to declare a constant variable.


As other people pointed out, from a semantic/linguistic point of view the expression constant variable is an oxymoron and, as such, we could argue about its correctness.

Quoting the specification, anyway, we can read

A variable of primitive type [...], that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

I suppose, hence, that we can accept (and consider correct) this binomial for our purpose.

like image 139
Luigi Cortese Avatar answered Sep 20 '22 21:09

Luigi Cortese