Title: Static things
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Static Things

Static Methods and Static Variables

The Java keyword can be associated with a method or a variable.

Rectangle.java


public class Rectangle {
    private int x, y, w, h;

    public Rectangle(int x, int y, int w, int h)
    {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;

        totalNumRectangles += 1;
        totalRectangleArea += w*h;
    }
    public int getArea()
    {
        return w*h;
    }
    public void setWH(int w, int h)
    {
        totalRectangleArea -= this.w * this.h;
        this.w = w;
        this.h = h;
        totalRectangleArea += this.w * this.h;
    }


    // Static things

    static private int totalNumRectangles = 0;
    static private int totalRectangleArea = 0;

    public static int getTotalNumRectangles()
    {
        return totalNumRectangles;
    }
    public static int getTotalRectangleArea()
    {
        return totalRectangleArea;
    }
    public static int getArea (int w_parm, int h_parm)
    {
        return w_parm * h_parm;
    }


    public static void main(String[] args) {
        // Note that I can call access static things without
        // constructing any Rectangles

        System.out.println(" Current Num Rectangles = " +
                getTotalNumRectangles());

        System.out.println(" Current Rectangle area = " +
                getTotalRectangleArea());

        System.out.println(" Area for width=2, height =4 is: "+
                getArea(2,4));
        System.out.println("********************************");


        //Rectangle r1 = new Rectangle();  // Can't do ... no default constructor

        Rectangle r1 = new Rectangle(1,1, 3, 5);
        Rectangle r2 = new Rectangle(4,4, 4, 5);

        System.out.println(" Area of r1 is: "+
             r1.getArea());
        System.out.println(" Area of r2 is: "+
                 r2.getArea());

        r2.setWH(2, 5);

        System.out.println("*****   Try static Totals again *********************");

        System.out.println(" Current Num Rectangles = " +
                getTotalNumRectangles());

        System.out.println(" Current Rectangle area = " +
                getTotalRectangleArea());



    }

}



RectangleDemo.java



public class RectangleDemo {


    public static void main(String[] args) {
        // Note that I can call access static things without
                // constructing any Rectangles

                System.out.println(" Current Num Rectangles = " +
                        Rectangle.getTotalNumRectangles());

                System.out.println(" Current Rectangle area = " +
                        Rectangle.getTotalRectangleArea());

                System.out.println(" Area for width=2, height =4 is: "+
                        Rectangle.getArea(2,4));
                System.out.println("********************************");


                //Rectangle r1 = new Rectangle();  // Can't do ... no default constructor

                Rectangle r1 = new Rectangle(1,1, 3, 5);
                Rectangle r2 = new Rectangle(4,4, 4, 5);

                System.out.println(" Area of r1 is: "+
                     r1.getArea());
                System.out.println(" Area of r2 is: "+
                         r2.getArea());

                // The following will run, but get a warning.
                System.out.println("getArea(4,5) = "+ r1.getArea(4,5));
                // The proper way to do it is:
                System.out.println("getArea(4,5) = "+ Rectangle.getArea(4,5));

                r2.setWH(2, 5);

                System.out.println("*****   Try static Totals again *********************");

                System.out.println(" Current Num Rectangles = " +
                        Rectangle.getTotalNumRectangles());

                System.out.println(" Current Rectangle area = " +
                        Rectangle.getTotalRectangleArea());



    }

}



Points to make on the above

1. Static variable - a variable that belongs to the class as a whole and not just to one object.
2. static methods cannot access instance variables like x,y,w, and h
3. static methods cannot call non static methods like getArea( ).
4. static methods cannot use the keyword "this"
5. static methods can call other static methods like getArea(int w, int h)
6. static variables can be accessed anywhere, including non-static methods (not demo'ed above)
8. Stacks are used for local variables. Stacks grow as we enter a "left-curly-brace" ... i.e. "{". The top of the stack is removed when we exit a "right-curly-brace" ... i.e. "}".
9. Whenever you use the "new" operator, Java keeps track of whether or not any reference(or pointer) exists for the created object. If nothing points to the object, we say that the object is orphaned. When the system needs to reclaim memory (perhaps it is running short), it goes through a Garbage Collection process where it will reclaim orphaned memory.

Consider the following program:


    public class RectangleDemo2 {
    static Rectangle rectangleStatic = new Rectangle(1,2, 10,20);

    void doit()
    {
        Rectangle rectangleLocal1 = new Rectangle(4,5, 30,10);

    } // As we exit, rectangleLocal becomes orphaned.

    Rectangle doit2()
    {
        Rectangle rectangleLocal2 = new Rectangle(4,5, 30,10);
        return rectangleLocal2;
    }

    public static void main(String[] args) {
        RectangleDemo2 rd = new RectangleDemo2();

        rd.doit();
        // At this point rectangleLocal1 is orphaned

        Rectangle rect = rd.doit2();
        // At this point rectangleLocal2 is NOT orphaned.

        // retangleStatic will stay around for the duration of
        // your application

    }

}



Examples of static things:

System - Note that we have never constructed any class for System. Go to onlline help and you can see all of the static things available in System. So the following are static things that we can call:

System.in - InputStream which is used when we do new Scanner(System.in)

System.out - A PrintStream that we use with System.out.println("Hi");

long time = System.currentTimeMillis( );

public static void main(String[] args) - Why is main static? When the JVM wants to launch your program it doesn't need to know anything about your programs constructors or anything else. It just collects the command line arguments into an array of Strings and calls main. It is up to main to call appropriate constructors and do whatever else is needed to execute your application.

Math Class

One of the best examples of a class with a lot of static methods.

static final double PI=3.14159....

static final double E=2.71828...

static double cos(double angle) : angle in radians

static double acos(double value) : returns angle in radians

static double toDegrees(double angleRadians)

static double toRadians(double angleDegrees)

Of course the other expected trig functions tan, atan, sin, asin are there

static double pow(double base, double exponent) : base ^exponent

static double random() : returns number between 0 and .9999999...

static double abs(double x) heavily overloaded

static double min(double x1, double x2) heavily overloaded

static double max(double n1, double n2) heavily overloaded

static long round (double x) - closest integer with ties rounding up

static double ceil(double x) - Returns the smallest whole number greater than or equal to the argument

static double floor(double x) - Returns the largest whole number less than or equal to the argument

static double sqrt(double x)



public class MathTest {

    public static void main(String[] args) {
        // Notice no extra import is needed because
        // the Math class lives in java.lang which is provided by default

        System.out.println("PI is "+
                Math.PI);

        System.out.println("E (Natural Log) is "+
                Math.E);

        double angleInRadians = Math.toRadians(60);
        System.out.println("cos(60) is "+
                Math.cos(angleInRadians));

        angleInRadians = Math.acos(0.50);
        double angleInDegrees = Math.toDegrees(angleInRadians);
        System.out.println("acos(.50) in degress is "+
                angleInDegrees);

        System.out.println("5 to the third power is "+
                Math.pow(5, 3));

        System.out.println(" random number "+
                Math.random());

        System.out.println("abs(-4) is "+
                Math.abs(-4));

        System.out.println("min(3, 6) is "+
                Math.min(3, 6));

        System.out.println("max(3, 6) is "+
                Math.max(3, 6));

        System.out.println("round(2.51) is "+
                Math.round(2.51));

        System.out.println("ceil(2.75) is "+
                Math.ceil(2.75));

        System.out.println("floor(2.75) is "+
                Math.floor(2.75));

        System.out.println("sqrt(64) is "+
                Math.sqrt(64));



    }

}



Self Test Exercises:

1. What values are returned by each of the following?
Math.round(3.2)   //3
Math.round(3.6)   //4
Math.floor(3.2)   //3.0
Math.floor(3.6)   //3.0
Math.ceil(3.2)    //4.0
Math.ceil(3.6)    //4.0
2. Suppose answer is a variable of type double. Write an assignment statement to assign Math.round(answer) to the int variable roundedAnswer.

int x = (int)Math.round(3.6);
3. Suppose n is of type int and m is of type long. What is the type of the value returned by Math.min(n, m)? Is it int or long

int n;
long m;
Math.min(n, m) returns a long
4. In DateSixthTry, which methods could be good to label as static?
dateOK(both versions), monthOK, monthString

Last Modified: June 2, 2014 4:32 PM