Wednesday, 21 January 2015

Java Constants

If you want to declare a constant in Java, you can do so with the final field modifier:

andrew@UBUNTU:~/Java$ cat Constant1.java
public class Constant1
  {
  public static void main(String args[])
    {
    final double PI = 3.14;
    System.out.println("PI = " + PI);
    }
  }
andrew@UBUNTU:~/Java$ javac Constant1.java
andrew@UBUNTU:~/Java$ java Constant1
PI = 3.14
andrew@UBUNTU:~/Java$


If you try to change one of these variables, you get a compilation error:

andrew@UBUNTU:~/Java$ cat Constant2.java
public class Constant2
  {
  public static void main(String args[])
    {
    final double PI = 3.14;
    System.out.println("PI = " + PI);
    PI = 22/7;
    }
  }
andrew@UBUNTU:~/Java$ javac Constant2.java
Constant2.java:7: cannot assign a value to final variable PI
    PI = 22/7;
    ^
1 error
andrew@UBUNTU:~/Java$