What's the difference between the two?
Is the only way to make a variable constant to add final
to it?
Integer HoursInDay = 24;
final Integer HoursInDay = 24;
Edit: I know this is a bland question, But I want to know the specifics
What's the difference between the two?
Is the only way to make a variable constant to add final
to it?
Integer HoursInDay = 24;
final Integer HoursInDay = 24;
Edit: I know this is a bland question, But I want to know the specifics
A constant variable means it can never be changed after it has been initialize once. By the way in java it's better to declare constant as follows -
public static final String CONSTANT_NAME = "constantName";
You are missing the static
keyword.
Remember, the only modifier that can be used with local variables is 'final'.
Final declares it immutable, once set, it cannot be changed and the compiler will take care of showing that to you. Additionally the JVM can optimize the access and be sure that sharing is not an issue memory-wise. A constant is final static
because you do want to say to the compiler that it can inline it and resolve at compile time, as well as make safe assumptions about the usage (no modification).