---
spec: JLS
title: "The Java Language Specification"
edition: "Java SE 12 Edition"
java_version: 12
chapter: "Chapter 13. Binary Compatibility"
section: "13.4.9"
heading: "13.4.9. final Fields and static Constant Variables"
parent: "13.4. Evolution of Classes"
source: https://docs.oracle.com/javase/specs/jls/se12/html/jls-13.html#jls-13.4.9
id: "13.4.9"
url: https://jvm.obfuscated.software/jls/se12/13.4.9.html
raw: https://jvm.obfuscated.software/jls/se12/13.4.9.md
---

# 13.4.9. `final` Fields and `static` Constant Variables

If a field that was not declared `final` is changed to be declared `final`, then it can break compatibility with pre-existing binaries that attempt to assign new values to the field.

**Example 13.4.9-1. Changing A Variable To Be `final`**

```
class Super { char s; }
class Test extends Super {
    public static void main(String[] args) {
        Super x = new Super();
        x.s = 'a';
        System.out.println(x.s);
    }
}
```

This program produces the output:

```
a
```

Suppose that a new version of class `Super` is produced:

```
class Super { final char s = 'b'; }
```

If `Super` is recompiled but not `Test`, then running the new binary with the existing binary of `Test` results in a `IllegalAccessError`.

Deleting the keyword `final` or changing the value to which a field is initialized does not break compatibility with existing binaries.

If a field is a constant variable ([§4.12.4](4.12.4.md)), and moreover is `static`, then deleting the keyword `final` or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for a usage of the field unless they are recompiled. This result is a side-effect of the decision to support conditional compilation ([§14.21](14.21.md)). (One might suppose that the new value is not seen if the usage occurs in a constant expression ([§15.28](15.28.md)) but is seen otherwise. This is not so; pre-existing binaries do not see the new value at all.)

The best way to avoid problems with "inconstant constants" in widely-distributed code is to use `static` constant variables only for values which truly are unlikely ever to change. Other than for true mathematical constants, we recommend that source code make very sparing use of `static` constant variables.

If the read-only nature of `final` is required, a better choice is to declare a `private` `static` variable and a suitable accessor method to get its value. Thus we recommend:

```
private static int N;
public static int getN() { return N; }
```

rather than:

```
public static final int N = ...;
```

There is no problem with:

```
public static int N = ...;
```

if `N` need not be read-only.
