Click to View the Video

LNK2LRN™2009/10

November 30 to December 18

AP Computer Science

Ch.7: Java Classes and Methods.

Semester Exam Review.

Weekly Plans and Assignments:

1. Monday(11/30): Presentations I of student game projects.

HW: Study Website Notes on Java Classes and Methods.

2. Tuesday(12/01): Presentations II of student game projects.

HW: Study Website Notes on Java Classes and Methods.

3. Wednesday(12/02): Presentations III of student game projects.

HW: Study Website Notes on Java Classes and Methods.

4. Thursday(12/03): Review of Java Classes and Methods. Writing the

FindMaxValue class. Prog7_01 Maximum Value of a Function in a Given

Interval. Here is the code that uses the FindMaxValue class.

HW: Finish Prog7_01 from class and turn-in tomorrow.

5. Friday(12/04): Prog7_02 Analysis of the Path of a Projectile.

HW: Finish Prog7_02 from class and turn-in tomorrow.

6. Monday(12/07): Writing Classes for Statistical Applications. The

MeanFinder, Median Finder, and ModeFinder classes. Prog7_03 Finding

the Mean, Median, and Mode. HW: Finish Prog7_03 from class and turn-in

tomorrow.

7. Tuesday(12/08): Writing the Variance class. Prog7_04 Finding the

Variance and Standard Deviation from a data set. HW: Finish Prog7_04

from class and turn-in tomorrow.

8. Wednesday(12/09): Writing the Permutation and Combination

classes. Prog7_05 Permutations and Combinations. HW: Finish Prog7_05

from class and turn-in tomorrow.

9. Thursday(12/10): Writing the Poisson Probability class.

Prog7_06 Calculating Poisson Probabilities. HW: Finish Prog7_06 from

class and turn-in tomorrow.

10. Friday(12/11): Writing the Hypergeometric Random Variable class.

Prog7_07 The Hypergeometric Random Variable. HW: Finish Prog7_07 from

class and turn-in Monday.

4. MONDAY(12/14): Review I for Semester Exam. All assigned

Homework Programs due, NO Exceptions. HW: Complete Review

Handout. Semester Folder check (50 pts.) due, NO Exceptions, during

your Semester Exam. 

5. TUESDAY(12/15): Period 1 Semester Exam. Shortened classes for

Periods 2-7. Review II for Semester Exam. HW: Study for Semester Exams.

6. WEDNESDAY(12/16): Late Start (10:30). Period 2 & 3 Semester

Exams. HW: Study for Semester Exams.

7. THURSDAY(12/17): Late Start (10:30). Period 4 & 5 Semester

Exams. HW: Study for Semester Exams.

8. FRIDAY(12/18): Late Start (10:30). Period 6 & 7 Semester Exams.

HW: Have a Safe and Happy Holiday Break!

 

Very Important: If you have any questions or were absent from class,

see me before school (8:00 - 8:30 AM), during Lunch, or after school.

Best to send an email to rpersin@fau.edu.

 

Website Notes - Ch.7: Java Classes and Methods.

Java utilizes the basic object technology found in C++. In a nutshell, the

Java language supports the idea of data packaging, or encapsulation,

through its mechanism. A Java class is an association between data

elements and/or functions, much like an extended struct in C (or a C++

class). In fact, there are no structs in Java at all; the mechanism of

grouping together similar elements is achieved only by creating a class.

The functional members of a class are referred to as the class methods.

Just as a C struct may contain other structs within it, a Java class may be

built on top of another class--although only one at a time--and inherit that

class's behaviors as well.

Java has its own syntax for describing methods and classes. It supports

public class members, which are visible outside the class; protected

members, which are visible only within the class and its subclasses; and

private members, which are only visible within that particular class.

Java supports abstract (virtual) classes, in which some or all of the member

functions are declared, but not defined--they have no function body, so that

only subclasses which fully define those functions may be used.

If you have some experience with C++ programming, many of these concepts

will be familiar to you. However, there are several striking differences between

C++ and Java.

Much of the implicit behavior that C++ takes for granted is absent in Java.

For example, there are no default constructors: a Java program must explicitly

call the operator new to create a new instance of a class.

In addition, arithmetic operators such as "+" or "= =" may not overload in Java.

There is no way for the programmer to extend the behavior of "+" beyond what

Java provides intrinsically. Another highly visible departure from C and C++ is

that there are no pointers (and logically, no pointer arithmetic) in Java.

Here is an example of a class called Sphere:

class Sphere {
static final double PI = 3.14;
static int count = 0;

double radius;

double xCenter, yCenter, zCenter;

Sphere(double theRadius, double x, double y, double z) {
radius = theRadius;

xCenter = x; yCenter = y; zCenter = z;
count++;
}

static int getCount() {
return count;
}

double volume() {
return 4.0 / 3.0 * PI * Math.pow(radius, 3);
}
}

 

Which is accessed by the program CreateSpheres:

public class CreateSpheres
{
public static void main (String[]args)
 {
    System.out.println("Number of Objects: " + Sphere.getCount());

    Sphere ball = new Sphere(4.0,0.0,0.0,0.0);
    System.out.println("Number of Objects: " + Sphere.getCount());

    Sphere globe = new Sphere(12.0,1.0,1.0,1.0);
    System.out.println("Number of Objects: " + Sphere.getCount());

//Volume
    System.out.println("Ball volume: " + ball.volume());
    System.out.println("Globe volume: " + globe.volume());
    }
}

Types of methods.

There are two types of methods.

(1) Instance methods are associated with an object and use the instance

variables of that object. This is the default.

(2) Static methods use no instance variables of any object of the class they

are defined in. If you define a method to be static, you will be given a rude

message by the compiler if you try to access any instance variables. You can

access static variables, but except for constants, this is unusual. Static

methods typically take all they data from parameters and compute something

from those parameters, with no reference to variables. This is typical of

methods which do some kind of generic calculation. A good example of this

are the many utility methods in the predefined Math class.

(See Math and java.util.Random).

Below is the program that finds the maximum value of a function in an interval.

public class MaxFinder {

public static double FindMaxValue(double a, double b) {
double y, large = -10000.0;
for (double j=a; j <= b + .00001; j = j + .01) {
y = (2.0 * Math.pow(j,4)) + 1.0 * Math.pow(j,3) - 3.0 * Math.pow(j,2);
if (y > large) large = y;
}
return large;
}


public static void main(String[] args) {
double x1, x2, maxvalue;

System.out.println("This program will find the maximum value of a function in an interval.");
System.out.println("The function is 2x^4 + x^3 - 3x^2.");
System.out.println("The interval extends from x1 to x2, inclusive.");

System.out.print("Enter the value of x1: ");
x1 = Keyboard.readDouble();
System.out.print("Enter the value of x2: ");
x2 = Keyboard.readDouble();

maxvalue = FindMaxValue(x1, x2);
System.out.println("Max value is " + Math.round(maxvalue*100.0)/100.0);
}
}


Qualifying a static call

From outside the defining class, an instance method is called by prefixing it

with an object, which is then passed as an implicit parameter to the instance

method,  inputTF.setText("");

A static method is called by prefixing it with a class nameMath.max(i,j);.

Curiously, it can also be qualified with an object, which will be ignored, but

the class of the object will be used.

Example

Here is a typical static method.

class MyUtils {
    . . .
    //================================================= mean
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the elements
        for (int i=0; i<p.length; i++) {
            sum += p[i];
        }
        return ((double)sum) / p.length;
    }//endmethod mean
    . . .
}

The only data this method uses or changes is from parameters (or local

variables of course).

Why declare a method static

The above mean() method would work just as well if it wasn't declared static,

as long as it was called from within the same class. If called from outside the

class and it wasn't declared static, it would have to be qualified (uselessly)

with an object. Even when used within the class, there are good reasons to

define a method as static when it could be.

(1) Documentation. Anyone seeing that a method is static will know how to

call it (see below). Similarly, any programmer looking at the code will know

that a static method can't interact with instance variables, which makes

reading and debugging easier.

(2) Efficiency. A compiler will usually produce slightly more efficient code

because no implicit object parameter has to be passed to the method.

Here is an example:

public class IndexFinder {

public static int find(int[] b, int num) {
     for (int j=0; j < b.length; j++) {
        if (b[j] == num) return j;
        }
        return -1;
        }

public static void main(String[] args) {
int index;
int a[] = {1, 3, 5, 7, 4, 5, 6, 9, 2, 0};
        for (int k=0; k < a.length; k++) {
            index = find(a, k);
            System.out.println("For " + k + " index is " + index);
            }
        }
}

Calling static methods

There are two cases.

(1) Called from within the same class
Just write the static method name. 
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
(2) Called from outside the class
If a method (static or instance) is called from another class, something

must be given before the method name to specify the class where the

method is defined. For instance methods, this is the object that the

method will access. For static methods, the class name should be

specified. 

// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);

If an object is specified before it, the object value will be ignored and

the the class of the object will be used.

Accessing static variables

Although a static method can't access instance variables, it can access static

variables. A common use of static variables is to define "constants".

Examples from the Java library are Math.PI or Color.RED. They are qualified

with the class name, so you know they are static. Any method, static or not,

can access static variables. Instance variables can be accessed only by

instance methods.

Alternate call

What's a little peculiar, and not recommended, is that an object of a class

may be used instead of the class name to access static methods. This is

bad because it creates the impression that some instance variables in the

object are used, but this isn't the case.

Review of Classes and Methods: Click HERE

Semester Exam Review Topics:

  1. History of computers. Changing number bases.

  2. Program Structure. Output in Java (Tracing Programs).

  3. Variables and Expressions. Calculations Using Java.

  4. Input in Java (Keyboard class). Data Types and Operators.

  5. Integer Data Types. Double Data Types. Converting Between Types.

  6. Arithmetic Operators. Doing Math in Java.

  7. Precedence and Order of Operations. Errors in Integer Arithmetic.

  8. Boolean Variables. Logical and Relational Operators.

  9. If Tests. Compound If Statements. Switch Statement.

  10. Loops and Program Flow. While and Do-While Loops.

  11. For Loops. Infinite Loops. Loops and If Tests Together.

  12. Curly Braces and Indenting. Sentinels and Counters.

  13. Nested If Statement. Initialization. Garbage Collection.

  14. Arrays. One and Two Dimensional Arrays. Subscripts.

  15. Initializing Arrays. Arrays and the For-Each Loop.

  16. FileIO. Methods and Classes.

Sample Exam Questions. Work on this at home.

The Back Burner

Back-Burner Assignments

(Click on the back burner of the stove for descriptions.)

1. Computerized Player Evaluation - due Nov. 16.
2. The Rhine Test - due Nov. 18.
3. The 23 Matches - due Nov. 20.
4. Your Own Game - due Nov. 30.
5. The AI Program - due Dec. 9.

 

 

animated open door gifThe Vault  

CH.1_Introduction to Computer Science  

CH.2_Java Basics 

CH.3_Char, Loop, Selection Statements 

Ch.4  Java Char and String Classes.

CH.5_Using Arrays in Java

CH.6  File IO in Java