ERROR ON PREV
Static Fields
  1. "Hello, World!"
  2. Variables and Types
  3. Arrays
  4. While, If, For
  5. ...Problem Set 0
  6. Static Methods
  7. Static Fields
  8. String Conversion
  9. Objects
  10. Threading
  11. Strings
  12. ...Problem Set 1.5
  13. Packages
  14. Complex Numbers
  15. Abstract classes
  16. Interfaces
  17. Autoboxing
  18. ...Problem Set 1
  19. enum
  20. Inner Classes
  21. Polymorphism
  22. Tanks!
  23. Callbacks
  24. Exceptions
  25. File I/O
  26. ...Problem Set 2
  27. Regular Expressions

Static Fields

Suppose we have a calculation that calls the Math.cos() a lot, but does it many times with the same argument. If the cos() funtion is time consuming, We might do something like this to optimize our code.

CosCache.java
1public class CosCache {
2    static double PI = 4.0*Math.acos(1.0/Math.sqrt(2.0));
3    static double lastCosArg = 0.0;
4    static double lastCosValue = 1.0;
5 
6    static double cos(double arg) {
7        if(arg != lastCosArg) {
8            lastCosArg = arg;
9            lastCosValue = Math.cos(lastCosArg);
10        }
11        return lastCosValue;
12    }
13 
14    public static void main(String[] args) {
15        PI = 3.14; // make sure PI is set!
16        double sum = 0;
17        for(int i=0;i<10;i++) {
18            if(i == 74) {
19                sum += cos(.7*PI);
20            } else {
21                sum += cos(.3*PI);
22            }
23        }
24        System.out.println("sum="+sum); 
25    }
26}
$ javac CosCache.java
$ java CosCache
sum=5.88171730331375

Here we've introduced three static fields.

  1. PI - This is supposed to hold the numerical value of pi.
  2. lastCosArg - This holds the last value we passed to the cos() function.
  3. lastCosValue - This is always equal to Math.cos(lastCosArg)

There is, of course, a small bug in this program. When we initialized we supplied a highly accurate value of PI by using 4.0*Math.acos(1/Math.sqrt(2.0)) (Note: acos() is the arc cosine).

One can prevent this sort of bug by making PI final. Final means that the value of PI cannot be changed.

CosCache2.java
1public class CosCache2 {
2    final static double PI = 4.0*Math.acos(1.0/Math.sqrt(2.0));
3    static double lastCosArg = 0.0;
4    static double lastCosValue = 1.0;
5 
6    static double cos(double arg) {
7        if(arg != lastCosArg) {
8            lastCosArg = arg;
9            lastCosValue = Math.cos(lastCosArg);
10        }
11        return lastCosValue;
12    }
13 
14    public static void main(String[] args) {
15        PI = 3.14; // make sure PI is set!
16        double sum = 0;
17        for(int i=0;i<10;i++) {
18            if(i == 74) {
19                sum += cos(.7*PI);
20            } else {
21                sum += cos(.3*PI);
22            }
23        }
24        System.out.println("sum="+sum);
25    }
26}
$ javac CosCache2.java
CosCache2.java:15: cannot assign a value to final variable PI
        PI = 3.14; // make sure PI is set!
        ^
1 error