简体   繁体   中英

Difference between a normal variable and a constant variable?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM