Midterm 2 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. Midterm 2 will concentrate on chapters 4 and 5. Programming is cumulative so you will need to understand the earlier material as well. You should review midterm 1 as well.
1. Within a class the order of method declaration
a) must be in lexicographic order.
b) must have main() declared first.
c) does not matter.
d) must be in the order called in main()
2. What does the following program print ?
class Test2 {
public static void main(String[] args)
{
int sum = 0;
int[] d = {3, 6, 9, 11, 15, 22};
for ( int j = 0; j < 6; ++j) {
sum += d[j];
System.out.println("sum = " + sum);
}
}
}
3. A method declaration must specify what about each formal parameter?
a) its size
b) its access specifier
c) its type
d) none of these
4. What gets printed?
class Test4 {
static int foo(int a) { return (a * a); }
static int foo(int a, int b) { return (a * b); }
static double foo(double a, double b) { return (a * b); }
public static void main(String[] args)
{
int i = 3, j = 6;
double x = 1.5, y = 2.0;
System.out.println( foo(i) );
System.out.println( foo(i +2, j -2) );
System.out.println(foo(x, y));
System.out.println( foo(foo(3, i)));
}
}
5. Is the following legal and if so what is printed?
6. Show the output that would be produced by the following program:class Test5 {
public static void main(String[] args) { int[] a1 = new int[5]; int[] a2 = new int[10]; a2 = a1; System.out.println(a2.length); } }
class Test6 {
public static void main(String[] args) {
int[] primes = {2, 3, 5, 7, 11, 13, 17};
int sum = 0;
for (int i = 1; i < primes.length; i++) {
sum = sum + (primes[i] + primes[i - 1]);
System.out.println("sum = " + sum);
}
}
}
7. Show the output that would be produced by the following program:
class Review7 {
static int goo(int i) { return i + 2; }
static void hoo(int[] d, int n) {
for (int i = 0; i < d.length; i++)
d[i] = goo(n);
}
public static void main(String[] args) {
int i = 2;
int[] a = {1, 2, 3};
System.out.println("goo =" + goo(i));
hoo(a, 1);
hoo(a, i);
for (i = 0; i < a.length; i++)
System.out.println(i + " : " + a[i]);
}
}