Final Review CMP12a Winter 2002 Ira Pohl
To get the answers - write up and run as code. You should also study the text review questions and review your programming assignments. Chapter 6 will be tested as will the previous work. Programming is cumulative so you will need to understand the earlier material as well. You should review both midterms as well.
1. Pick the best answer for the following four statements
Within a class:
a) data members can be public
b) members can appear in arbitrary order
c) constructor declarations can be overloaded
d) all of the above
e) none of the above
A static method:
a) can be private
b) is also known as a class method
c) can access private members from the class
e) all of these
f) none of these
An instance method:
a) cannot be private
b) can be static
c) can use the this reference
e) all of these
f) none of these
The keyword final
a)can be used in main()
b) is a return type
c) means the variable is a constant
e) all of these
f) none of these
2. What does the following program print ?
class Test2 {
public static void main(String[] args)
{
pair p = new pair(9, 5);
int[] d = {2, 4, 6, 8};
for ( int j = 0; j < 6; ++j) {
if (j % 2 == 0)
d[j] += p.first;
else
d[j] += p.second;
System.out.println("d[j] " + d[j]);
}
}
}
public class pair { public int first, second; }
3. Add a method plus that adds the values of two pairs.
Do it as an instance method and a static method. So it can be called either
as p.plus(q) or plus(p,q) in both cases the return
type should be a pair. Write a main() that tests this.
4. Add a constructor to pair that initializes
a pair from an existing pair. This will allow the declaration.
pair p = new pair(1,1);
pair q = new pair(p); //uses copy constructor
5. What gets printed?
class Test5 {
static int foo(int a) {
if (a < 1) return 1;
else return 2 + foo(a-1) ; }
static int foo(int a, int b) { return foo(a) + foo(b) ; }
public static void main(String[] args)
{
int i = 6, j = 3, k = -1;
System.out.println( foo(k) );
System.out.println( foo(i) );
System.out.println(foo(i, j));
}
}
6. Assume you did problems 2-4 and include this code for pair. Is the following legal and if so what is printed?
class Test6 {
public static void main(String[] args)
{
pair p1 = new pair(1,1);
pair p2 = new pair(2,2);
System.out.println(p2.first);
p2 = p1;
System.out.println(p2.first);
System.out.println(p2.plus(p1).first);
}
}
7. Show the output that would be produced by the following program:
class Test7 { public static void main(String[] args) { int[] confusing = {1, 2, 3, 4, 5, 6}; int sum = 0;
for (int i = 1; i <4; i++) { sum = sum + (confusing[confusing[i]]); System.out.println("sum = " + sum); } } }