+ 1
What is the best way to declare constant variable in a class.??
public static final int a=0; Or public final int a=0;
6 Respuestas
+ 6
It's not about which is best, it's about scope.
The difference between the two was - the first works for class scope (static scope), while the second works for instance scope, meaning an instance is necessary to use the constant.
+ 4
Depends on whether you want them to be class variables or member variables
+ 3
It depends. Static variables are shared across all instances of the class (and can be accessed even without an instance). Nonstatic values are bound to the instance.
+ 3
Joshua static and final serve two different purposes.
final means that you cannot ever assign a new value to that variable. Sometimes this is important, to give the compiler some guarantees that a value is not going to change in the middle of a complex operation, for example when working with the Stream API. But these "final" values do not always need to be shared across all instances.
This might be a bit advanced but I post it anyway: https://www.baeldung.com/java-lambda-effectively-final-local-variables
You are right that by using static, only a single area of memory is occupied, so this can be useful to reduce the memory consumption of the program.
+ 3
Declare the variable final
+ 1
Joshua exactly.
This is an example for a constant property that is initialized in the constructor.
(although usually we would explicitly write getters and setters instead of directly changing instance properties.)
https://code.sololearn.com/cbV64dNvChwv/?ref=app