Review for Midterm 1

One-page version suitable for printing.

Question 1-1

In your own words, describe what distinguishes a class variable from an instance variable. (I'm not asking about how you distinguish them syntactically in Java --- I'm asking how their behavior is different.)

Solution

Question 1-2

What is the purpose of a constructor method?

Solution

Question 1-3

Write a program that reads a line from the user and says ``ok'' if the user's line represents a valid integer, and ``bad'' otherwise.

Type something. -56a2
bad
Use Integer.parseInt(s), which converts the string s to an int; if the string isn't formatted correctly, the class method throws a NumberFormatException.
import csbsju.cs160.*;
public class Example {
    public static void main(String[] args) {


    }
}

Question 1-4

[Covers material not covered this semester yet.]

Solution

Question 1-5

Complete the following definition of a bank. The bank should be able to support up to 100 accounts. Do not worry about what happens if a 101st account is added to the bank.

public class Bank {
    Account[] acct;
    int num_acct;

    public Bank() {


    }
    public int getNumAccounts() { return num_acct; }
    public Account getAccount(int which) {
        // returns the whichth account in the bank


    }
    public void addAccount(Account what) {
        // adds what into the bank


    }
}

Question 1-6

Recall the Account definition methods.

double getBalance()
Returns the amount of money held in the object account.

void deposit(double amt)
Adds amt dollars to the object account's balance.

void withdraw(double amt)
Subtracts amt dollars from the object account's balance.

Complete the following method that employs the above definition to find the total amount of money deposited in the bank.

public class BankFunctions {
    public static double totalAssets(Bank bank) {



    }
}

Solution

Question 1-7

Name the primitive types of Java. (There are eight of them.)

Solution

Question 1-8

[Covers material not covered this semester.]

Solution

Question 1-9

Consider the following two class definitions.

class X {
  public double g(double x) {
    return f(x) * f(x);
  }
  public double f(double x) {
    return x + 1.0;
  }
}

class Y extends X {
  public double f(double x) {
    return x + 2.0;
  }
}
What will the following sequence of statements print?
Y y = new Y();
X x = y;
IO.println(y.f(2.0));
IO.println(x.f(2.0));
IO.println(x.g(2.0));

Solution