8.3. C# constants and read-only fields (Java final variables)

In Java, a final variable is one whose value cannot be reassigned once it has been given a value. You can only use a final variable after it has been assigned a value – all final variables must be assigned values at some point in time before its first use, otherwise the compiler complains.

In Java:

 1:  // FinalTest.java
 2:  public class FinalTest{
 3:    final int FINAL_VAR;
 4:
 5:    public FinalTest(int newValue){
 6:      FINAL_VAR = newValue; // compilation error if
                                   omitted.
 7:    }
 8:
 9:    public static void main(String args[]){
10:      FinalTest f = new FinalTest(4);
11:    }
12:  }

If FINAL_VAR has been declared with the static modifier too on line 3, you will have to either:

  • initialize it in the same ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.