We make use of both static and const variables in different languages. In this section, we will describe the difference points between both variables. Let's discuss.
A static variable is a class property that is used in a class and not on the instance of the class. The variable is stored on the data segment area of the memory, and the same value is shared among every instance created in a class. To use a static variable, we use the static keyword. We can use the static keyword for making a static value, a static function, with classes, operators, properties and work as a utility function for the application or websites. The value of a static variable is set at the run time and is a kind of global value that can be used for the instance of the specified class.
A const variable is a variable that has a fixed value and remains the same throughout the program. A property of the const variable is that we cannot change or modify its value throughout the program. It is because as soon as we make a const value, the compiler gets informed that the value is fixed and should be prevented from the programmer. Thus, whenever the programmer tries to modify a const value, an error gets displayed that the const value cannot be changed. To use a const variable, we use a 'const' keyword and input value.
There are the following difference points which will let us understand the difference between the two:
In the above program code, we can see that a static method is created within a class and when it is invoked, it calls the statement within the static method of the class. The output of the following is shown below:
In the above code, it is seen that the const variable is assigned with a value but when we try to re-assign another value, an error is thrown which tells that the value described as const cannot be changed. Hence, the output of the above code is:
In this section, we understood that static as well as const variable have different roles and are used for different purposes where a static variable can be used for a class method or property and a const variable is used for initializing a const value for an array, variable or an object.