The difference between Java’s “final” and C#’s “const”

Final in Java is used to declare a class that can’t be subclassed, a method that can’t be overridden, or …

A final variable means the value won’t change, but the value can still be determined at run time:

final int i;
if ( j > 0 ){
   i =1;
} else {
   i = 2;
}

You get a compile time error if the final variable isn’t definitely unassigned anytime you assign to it:

final int i;
if(j>0){
   i=1;
}
if(a<10){
   i=1;
}

In C#, a "const" must be determined at compile time.

Leave a Reply