O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required