+ 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;

27th Sep 2020, 5:00 AM
shrijith
shrijith - avatar
6 Antworten
+ 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.
27th Sep 2020, 5:13 AM
Ipang
+ 4
Depends on whether you want them to be class variables or member variables
27th Sep 2020, 5:14 AM
Jeremy
Jeremy - avatar
+ 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.
27th Sep 2020, 5:12 AM
Tibor Santa
Tibor Santa - avatar
+ 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.
27th Sep 2020, 6:28 AM
Tibor Santa
Tibor Santa - avatar
+ 3
Declare the variable final
28th Sep 2020, 2:00 AM
Aaruni Tiwari
Aaruni Tiwari - avatar
+ 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
27th Sep 2020, 7:34 AM
Tibor Santa
Tibor Santa - avatar