Friday, May 27, 2005

Constants

"The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change." (Wikipedia 2006)
FORTRAN manual for Xerox computers

Introduction

Constants are called final variables in Java. Variables that should never change value should be declared final Constants are usually declared public static final. PI is for example declared as public static final double PI = 3.14159265358979323846; (and as you may have observed, the value of PI did actually change since the FORTRAN days...)

Program

package bloggingjava;

class Main {
    public static void main(String[] args) {
        final int MONTHS;
        MONTHS = 12;
        // MONTHS = 13; // error, already assigned
        System.out.println("MONTHS: " + MONTHS);
    }
}

Output

MONTHS: 12

References

No comments: