47
Class Variables

Class Variables - UW Faculty Web Serverfaculty.washington.edu/jstraub/JavaClass/Slides/module... · 2014. 6. 22. · Floating Point Types: Pre‐Defined Constants • The Float and

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

  • Class Variables

  • Class Methods• Class methods are declared using the static keyword.• Class methods are referenced using the class name.

    public class Arithmetic{

    // Return the larger of two valuespublic static int larger( int parm1, int parm2 ){

    int rval = 0;

    if ( parm1 > parm2 )rval = parm1;

    elserval = parm2;

    return rval;}

    }

    int bigger = Arithmetic.larger( inx, jnx );

  • The MathOp Utility Classpublic class MathOp{

    /** Return the value of 2 to the power expo. */public static int powerOf2 (int expo){

    int power = 1;for ( ; expo > 0; expo--)

    power = power * 2;return power;

    }

    ...

    continued on next slide

  • The MathOp Utility Class.../** Return sum / count rounded to the nearest int. */public static int average (int sum, int count){

    int avg = 0;if (sum >= 0)

    avg = (sum + count / 2) / count;else

    avg = (sum - count / 2) / count;

    return avg;}

    }

    continued

    This technique for computing an

    average is from your textbook.

  • Private ConstructorsUse private constructors to prevent a class from being instantiated.

    public class MathOp{

    private MathOp(){

    super();}. . .

    }

  • The Java Math Class

    • See the Java math class (java.lang.math) for an example of a large utilities class. 

  • Float And Double Types• The float and double types are used to store real numbers such as 3.14...• ... they represent numbers in scientific notation, using an exponent and a 

    mantissa, for example, 4.759 x 1027. 

    public class FloatTest{

    public static void main( String[] args ){

    double dval = 3.14;System.out.println( 3.14 * 22.9 ); // 71.905System.out.println( 9.0 / 2 ); // 4.5

    }}

  • Floating Point Types: Range and Precision

    • The range of a floating point type is the approximate range of numbers that it can store. 

    • The precision of a floating point type is the approximate number of digits that can be accurately stored in the mantissa. 

    Type Range ApproximatePrecisionfloat 10‐45 to 1038 8double 10‐324 to 10308 17

  • Floating Point Types: Rounding Errors

    • Some decimal numbers require an infinite number of digits (or bits) to store a precise value... 

    • ... but double, for example, has only 52 bits in which to store a mantissa...• ... so rounding errors are occasionally going to occur.

    System.out.println( .1 + .2 ); // .30000000000000004System.out.println( 1.0 / 9 ); // .1111111111111111

    252 = 4.5... x 1015= about 16 digits + magic = about

    17 digitsAnswer is

    correct to 16 digits

  • Floating Point Types: Testing For Equality

    • Floating point rounding errors make testing two values for equality problematic.

    public static void main( String[] args ){

    double aaa = 0.7;double bbb = 0.9;double xxx = aaa + 0.1;double yyy = bbb - 0.1;System.out.println( "x = " + xxx + ", y = " + yyy );System.out.println( "x == y: " + (xxx == yyy) );

    }Output:x = 0.7999999999999999, y = 0.8x == y: false

  • Floating Point Types: Epsilon Test For Equality

    • Test two floating point numbers using the epsilon test:

    public static void main( String[] args ){

    double aaa = 0.7;double bbb = 0.9;double xxx = aaa + 0.1;double yyy = bbb - 0.1;double eps = .00001;boolean equ = Math.abs( xxx - yyy ) < eps;System.out.println( "x = " + xxx + ", y = " + yyy );System.out.println( "x == y: " + equ );

    }Output:x = 0.7999999999999999, y = 0.8x == y: true

  • Floating Point Types: Constants• The Java compiler recognizes the following floating point constants:

    Constant Type1. double1.0 double1d or 1D double1e30 double (1030)1e30d or 1e30D double (1030)1f or 1F float1e30f or 1e30F float (1030)

  • Floating Point Types: Pre‐Defined Constants

    • The Float and Double classes define the following constants:

    Constant ValueFloat.NaNDouble.NaN not‐a‐number

    Float.MAX_VALUEDouble.MAX_VALUE maximum value

    Float.MIN_VALUEDouble.MIN_VALUE minimum value

    Float.POSITIVE_INFINITYDouble.POSITIVE_INFINITY positive infinity

    Float.NEGATIVE_INFINITYDouble.NEGATIVE_INFINITY negative infinity

  • Floating Point Types: Special Values• Java uses some of the special constants from the previous slide to indicate 

    exceptional conditions:

    public class Test{

    public static void main( String[] args ){

    System.out.println(1e200 * 1e200 );System.out.println( 1e200 * -1e200 );System.out.println( Math.sqrt( -1 ) );

    }}Infinity‐InfinityNaN

  • Exercises1. Add two class methods to the MathOp class:

    // Computes the circumference of a circlepublic static double circumference( double radius )

    // Computes the area of a circlepublic static double area( double radius )

    2. Textbook, Chapter 5, page 5‐3Exercises 5.1 and 5.2

  • Declaring Class Variables• Class variables are declared outside of any method, and use the static 

    keyword:

    public class Person{

    private static int numPersons_ = 0;private String firstName_;private String lastName_;...public static int getNumPersons(){

    return numPersons_;}

    }

    Class variable

    Instance variables

  • Using Class Variables (1)• Like class methods, class variables are available at any time; they have the 

    same value across all objects:

    public class Person{

    ...public Person(){

    firstName_ = "none";lastName_ = "none";++numPersons_;

    }...

    }

  • Using Class Variables (2)• Access class variables using the class name:

    public static void main(String[] args){

    System.out.println( Person.getNumPersons() );Person magilla = new Person( "who", "else" );System.out.println( Person.getNumPersons() );Person zilla = new Person( "George", "Washington" );System.out.println( Person.getNumPersons() );System.out.println( magilla.getNumPersons() );System.out.println( zilla.getNumPersons() );

    }

    Non-standard usage; use Person.getNumPersons()

  • Variable And Parameter Name Scope

    The scope of a variable or parameter name is the same as its visibility in a program:

    Identifier Scope (Visibility)

    Class variable Entire class.

    Instance variable All instance methods and constructors in a class.

    Local variable (declared in method)

    Point of declaration to end of declaring method.

    Local variable (declared in for loop) The for loop.

    Local variable (declared in compound statement)

    Point of declaration to end of declaring compound statement.

  • Exercises1. The following program doesn’t compile; why not? Fix the program.

    public class ScopeTest{

    public static void main(String[] args){

    int temp = 5;for ( int inx = 0 ; inx * temp < 50 ; ++inx )

    new Turtle();System.out.println( inx + " Turtles created" );

    }}

    2. The following program is intended to use a Turtle to draw a line 1000 pixels long, but it doesn’t work; why not? Fix the program.public class ScopeTest{

    public static void main(String[] args){

    for ( int inx = 0 ; inx < 10 ; ++inx ){

    Turtle sam = new Turtle();sam.paint( 0, 100 );

    }}

    }

  • The final Keyword• Declaring something final in Java means that it can’t be changed.• Use final with variables and parameters to indicate that they are not going 

    to change.• When a value cannot be changed the compiler can use it to write more 

    efficient code.• Use final to declare named constants, such as PI.• When certain variables and parameters are declared as unchangeable 

    (final) your code can be easier to read, and easier to maintain.

  • Final Parameters (1 of 2)• It is considered bad coding practice to modify parameters:

    // DON’T do thisprivate static double factorial( int num ){

    int result = num;while ( --num > 0 )

    result = result * num;return result;

    }

    // DO thisprivate static double factorial( int num ){

    int result = 1;for ( int inx = num ; inx > 0 ; --inx )

    result = result * inx;return result;

    }

  • Final Parameters (2 of 2)You can declare your parameters final, which will:• Prevent you (or anyone else) from changing the parameter;• Document for readers that your parameter will not change.

    // DO thisprivate static double factorial( final int num ){

    int result = 1;for ( int inx = num ; inx > 0 ; --inx )

    result = result * inx;return result;

    }

  • Final Local Variables (1 of 2)• Use local variable constants to avoid “magic numbers”:

    // DON’T do thisprivate double newHeading( final double degrees ){

    double heading_ = currHeading_ + degrees * Math.PI / 180;

    return heading_;}

    // DO thisprivate double newHeading( final double degrees ){

    final double TO_RADIANS = Math.PI / 180;double heading_ =

    currHeading_ + degrees * TO_RADIANS;return heading_;

    }

  • Final Local Variables (2 of 2)• In Java, a final local variable can be dynamically initialized from a 

    parameter:

    private static voidtripStats( final double miles, final double minutesElapsed ){

    final double MPH = miles / (minutesElapsed / 60);// . . .

    }

  • Final Class Variables (1 of 2)• This is the most common use of final variables.• Can be private, but are typically public.

    public class Test{

    public static Color BG_COLOR = Color.BLUE;public static Color OUTLINE_COLOR = Color.RED;public static Color HIGHLIGHT_COLOR = Color.YELLOW;...

    }

  • Final Class Variables (2 of 2)• Final class variables may be initialized in a constructor, but that’s a bad 

    idea:public static void main( String[] args ){

    Test test1 = new Test( Color.RED, Color.MAGENTA, Color.CYAN );System.out.println( Test.BG_COLOR );Test test2 = new Test( Color.PINK, Color.MAGENTA, Color.CYAN );System.out.println( Test.BG_COLOR );

    }

    private Test( Color bground, Color out, Color high ){

    BG_COLOR = bground;OUTLINE_COLOR = out;HIGHLIGHT_COLOR = high;

    }Output:java.awt.Color[r=255,g=0,b=0]java.awt.Color[r=255,g=175,b=175]

  • Final Instance Variables• Final instance variables may be initialized in a constructor.

    public class Test{

    public Color BG_COLOR;public Color OUTLINE_COLOR;public Color HIGHLIGHT_COLOR;

    private Test( Color bground, Color out, Color high ){

    BG_COLOR = bground;OUTLINE_COLOR = out;HIGHLIGHT_COLOR = high;

    }}

  • Exercises1. Rewrite the GuessNumber class so that it uses final class variables to store the search 

    limits. In addition to adding the constant variables, you will have to modify askUsersFirstChoice and askUsersNextChoice.

    2. In GuessNumber, change the final class variables to final instance variables. Rewrite the constructor so that the values of the variables are set from parameters passed to the constructor.

    3. Create a class named Days. Within the class create seven final integer class variables, each named after a day of the week. Give SUNDAY an initial value of 0, MONDAY and intial value of 1, etc.

    4. Write a test program with a main method that uses the Days class to print out the number of each day of the week; for example: 

    System.out.println( "Sunday = " + Days.SUNDAY );

  • Primitive Types• Java, like most languages, supports primitive data types, typically numeric 

    types that can be processed quickly and efficiently by your computer.

    Primitive Type Width (bits) Comment

    int 32 Integer type

    byte 8 Integer type

    short 16 Integer type

    long 64 Integer type

    char 16 Unsigned integer type for storing Unicode values

    float 32 Real number type

    double 64 Real number type

    boolean undefined true or false

  • Primitive Types As Arguments (1 of 2)

    • When a primitive type is passed as an argument to a method, a copy is made and stored in the parameter list:

    paint parameter list

    145.7

    156

    main local variables

    7c42a91344cb64

    145.7

    156

    public static void main( String[] args ){

    Turtle todd = new Turtle();double degree = 145.7;double length = 156;todd.paint( degree, length );

    }

  • Primitive Types As Arguments (2 of 2)

    • Changing a parameter merely changes the value in the parameter list; it does not affect the original variable:

    paint parameter list

    ‐156  42

    main local variables

    ‐156

    public static void main( String[] args ){

    int inx = -156;test( inx );System.out.println( inx );

    }

    private static void test( int param ){

    param = 42;System.out.println( param );

    }

    Output:42‐156

  • Reference Types• In Java all objects are reference types. The value stored in a local variable 

    is a reference to a block of memory that stores the object’s properties:

    main local variables

    7c42a91344cb64

    public static void main( String[] args ){

    Turtle todd = new Turtle();...

    }

    current colorcurrent positioncurrent directionetc.

  • Reference Types As Arguments (1 of 2)

    • When a reference type is passed as an argument to a method, the associated parameter points to the original object data:

    main local variables

    7c42a91344cb64

    public static void main( String[] args ){

    Turtle todd = new Turtle();test( todd );...

    }

    current colorcurrent positioncurrent directionetc.

    test parameter list

    7c42a91344cb64

  • Reference Types As Arguments (2 of 2)

    • Using a parameter to change an object can change the original object:

    public static void main( String[] args ){

    Turtle myrtle = new Turtle();myrtle.fillBox( 64, 64 );test( myrtle );myrtle.fillBox( 64, 64 );

    }

    current colorcurrent positioncurrent directionetc.

    private static voidtest( Turtle param ){

    param.move( 0, 128 );param.switchTo( Turtle.RED );

    }

  • Exercises1. Enter, compile and execute the code from the preceding slide, illustrating how myrtle’s 

    properties can be changed from a method.

    2. Change the test method in the previous exercise to look like this:private static void test( Turtle param ){

    param = new Turtle();param.move( 0, 128 );param.switchTo( Turtle.RED );

    }How does the behavior of the program change? Explain why.

  • String Method: Length• The lengthmethod of the String class returns the length of the string.public class Test{

    public static void main( String[] args ){

    String response =JOptionPane.showInputDialog( null, "Enter four chars.");

    if ( response.length() != 4 )JOptionPane.showMessageDialog( null, "I said FOUR chars." );

    }}

  • Strings: Indexing• The characters in a string may be referred to by their index...• ... the first character is at index 0...• ... the last character is at index length – 1.

    see spot run0   1   2   3   4   5   6   7    8   9  10 11

    length = 12

    public static void main( String[] args ){

    String test = "see spot run";String sub1 = test.substring( 4, 8 );String sub2 = test.substring( 9 );System.out.println( sub1 );System.out.println( sub2 );

    }

  • Strings: Indexing• The characters in a string may be referred to by their index...• ... the first character is at index 0...• ... the last character is at index length – 1.

    see spot run0   1   2   3   4   5   6   7    8   9  10 11

    length = 12

  • String Method: SubstringThere are two methods that return a substring of a string:

    substring( int start, int end )Returns a substring beginning at character start, and ending at character end – 1.

    substring( int start )Returns a substring beginning at character start, and continuing through the end of the string.

  • Substring Examplespublic static void main( String[] args ){

    String test = "see spot run";String sub1 = test.substring( 4, 8 );String sub2 = test.substring( 9 );System.out.println( sub1 );System.out.println( sub2 );

    }

    Output:spotrun

  • ChainingChaining refers to the use of values returned by methods to invoke other methods:

    public static void main( String[] args ){

    String sStart = getNextVic().getPosition().substring( 0, 1 );

    int iStart = Integer.parseInt( sStart );System.out.println( sStart + ", " + iStart );

    }

    private static Vic getNextVic(){

    return new Vic();}

  • Random Numbers RevisitedProblem:

    Write a method, int nextInt( int start, int end ), that uses java.util.Random to return an integer, next, such that: start 

  • Random Numbers Revisited: A Test Method

    Problem:Add a private test method to RandomTest, void test( int start, intend, int tries ), which will invoke nextInt( start, end ) tries times and print the result each time, terminating the program if the test fails.

    private void test( int start, int end, int tries ){

    System.out.print( "start: " + start );System.out.print( ", end: " + end );System.out.println( ", tries: " + tries );...

    continued on next slide

  • Random Numbers Revisited: A Test Method

    ...for ( int inx = 0 ; inx < tries ; ++inx ){

    int next = nextInt( start, end );System.out.print( next + ": " );if ( next >= start && next < end )

    System.out.println( "CORRECT" );else{

    System.out.println( "WRONG" );System.exit( 1 );

    }}

    }

    continued

  • Random Numbers Revisited: A Test Driver

    Problem:Add a main method to RandomTest that will call test passing a variety of values to exercise nextInt( int, int ): 

    public static void main(String[] args){

    RandomTest tester = new RandomTest();tester.test( 0, 100, 100 );tester.test( 25, 50, 100 );tester.test( 10000000, 20000000, 100 );tester.test( -5, 5, 100 );tester.test( -200, -150, 100 );

    }

  • Exercises1. Write a program that:

    a) Uses JOptionPane.showInputDialog to ask the user to enter a string.b) Uses java.util.Random to generate a number, start, such that 0