1

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

Razib
  • 10,965
  • 11
  • 53
  • 80
FatFockFrank
  • 169
  • 1
  • 4
  • 17
  • 1
    duplicate of http://stackoverflow.com/questions/15655012/how-final-keyword-works ? – pL4Gu33 Mar 03 '15 at 19:09
  • 2
    Remember to use `UPPER_CASE_UNDERSCORE` for constants. Makes it easier for other developers to understand the intention. – Obicere Mar 03 '15 at 20:24

2 Answers2

2

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'.

Community
  • 1
  • 1
Razib
  • 10,965
  • 11
  • 53
  • 80
1

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).

ReneS
  • 3,535
  • 2
  • 26
  • 35