Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between final variables and compile time constant

What is the difference between final variables and compile time constants?

Consider the following code

final int a = 5; final int b; b=6; int x=0; switch(x) {      case a: //no error      case b: //compiler error } 

What does this mean? When and how are final variables assigned a value? What happens at run time and what happens at compile time? Why should we give switch a compile time constant? What other structures of java demands a compile time constant?

like image 976
Tarun Mohandas Avatar asked Mar 09 '13 10:03

Tarun Mohandas


People also ask

What is the difference between constant and final variable?

The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object's entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.

What is a compile-time constant?

A compile-time constant is a value that can be (and is) computed at compile-time. A runtime constant is a value that is computed only while the program is running. If you run the same program more than once: A compile-time constant will have the same value each time the application is run.

What is the difference between variables and constants Java?

Constants usually represent the known values in an equation, expression or in line of programming. Variables, on the other hand, represent the unknown values. Constants are used in computer programming. Variables also have its uses in computer programming and applications.

What is difference between final and const in Dart?

The final keyword in Dart is used to create constants or objects that are immutable in nature. The only difference between the final and const keyword is that final is a runtime-constant, which in turn means that its value can be assigned at runtime instead of the compile-time that we had for the const keyword.


1 Answers

The problem is, that all case: statements must be ultimate at compile time. Your first statement is ultimate. a will for 100% be no other value than 5.

final int a = 5; 

However, this is not guaranteed for b. What if there would be an if-statement around b?

final int b; if(something())    b=6; else    b=5; 
like image 124
poitroae Avatar answered Oct 04 '22 05:10

poitroae