What is the difference between constant variables and final variables in java?

前端 未结 4 829
感情败类
感情败类 2020-12-31 02:27

Please help me understand the difference between constant variables and final variables in Java. I am a bit confused with it.

4条回答
  •  悲哀的现实
    2020-12-31 02:49

    There are several values in the real world which will never change. A square will always have four sides, PI to three decimal places will always be 3.142, and a day will always have 24 hours. These values remain constant. When writing a program it makes sense to represent them in the same way - as values that will not be modified once they have been assigned to a variable. These variables are known as constants.

    Declaring a Variable as a Constant

    In declaring variables I showed that it’s easy to assign a value to a int variable:

    int hoursInADay = 24;
    

    We know this value is never going to change in the real world so we make sure it doesn’t in the program. This is done by adding the keyword modifier final:

    final int HOURS_IN_A_DAY = 24;
    

    In addition to the final keyword you should have noticed that the case of the variable name has changed to be uppercase as per the standard Java naming convention. This makes it far easier to spot which variables are constants in your code.

    If we now try and change the value of HOURS_IN_A_DAY:

    final int HOURS_IN_A_DAY = 24; 
    HOURS_IN_A_DAY = 36;
    

    we will get the following error from the compiler:

    cannot assign a value to final variable HOURS_IN_A_DAY

    The same goes for any of the other primitive data type variables. To make them into constants just add the final keyword to their declaration.

    Where to Declare Constants

    As with normal variables you want to limit the scope of constants to where they are used. If the value of the constant is only needed in a method then declare it there:

    public class Hours {
       public static final int HOURS_IN_A_DAY = 24;
    }
    

提交回复
热议问题