What is the point in using final int when just int will accomplish the same task?

2018-04-10 12:05 am
In Java, you use final int to set an arrays length, but you can use just normal variable to do the same thing.
Ex: final int MAX is the same as int max
I see no difference and believe I can use a normal variable integer. Am I wrong?

回答 (3)

2018-04-10 12:16 am
✔ 最佳答案
You are right in that any variable can be treated by a programmer as if it were a constant. However, there are a few reasons why it is good to declare constants if you can.

If you are declaring a constant, the Java Virtual Machine can assume that it only needs a set amount of space in storage. If you are trying to make a program that is as efficient as possible, constant declaration is the way to go. I am not
sure how familiar you are with binary, but for example, the unsigned integer 2 can be written in binary as 10, which only needs two pieces of information (known as bits). On the other hand, the unsigned integer 50 needs six bits, 110010. Most Java ints reserve 32 bits of space and can hold any number between -2,147,483,648 and 2,147,483,647. If you can tell the computer "Hey, I only need two bits to hold this information" that can save a lot of space.

Second (and more likely to come up), you may not always be writing final products. Let's say that at some point in the future you are writing a new Java library. Basically, you are expanding the language of Java itself. Your code (and your variables) are going to be used in other people's programs. If there is some variable that should never change (like Pi, for example), you should set it as final. That way, no one can change the value assigned to that variable.
2018-04-10 11:26 am
It can help prevent accidental changes. If you have a brain fart and try to change a value that shouldn't be changed, the compiler will yell at you.

Relatedly, it can help with debugging. If you see something declared as "final", then you *know* what the value is, and don't have to spend time finding out what the value *really* is.
2018-04-10 1:43 am
You have some good answers already. I'll point out that upper and lower case matters, so "int max=999;" is *not* the same as "final int MAX=999;".

Also, symbolic constants are usually used in more than one method, and at the class level they should also be declared "static". Also, the default visibility is usually wrong. Most of the time, a constant should be declared "public" or "private". A good example is:

public final static int MAX_ENTRIES = 999;

Admittedly, if you're writing a tiny application that all fits in one source file, none of this matters much. (However, you won't be able to use the constant in main() or any other static method unless you declare it as static.)


收錄日期: 2021-05-01 22:15:17
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20180409160533AAmAzrj

檢視 Wayback Machine 備份