PRELIM 2 SAMPLE QUESTIONS
Prelim 2 concentrates on what we have covered since
Prelim 1 (up through Program 3) but will also include material covered by
Prelim 1. Arrays are NOT covered.
· Draw objects as rectangles with dashed borders containing the object's instance variables.
· Each object should contain two compartments separated by a dashed line.
· The upper compartment should contain the object's instance variables; the lower compartment should show the object's instance methods.
· Each variable should be drawn as a solid rectangle. The name of the variable should appear to the left of the rectangle, and the contents of the variable should be written in the rectangle.
· Draw object references as arrows pointing to the objects to which they refer.
b) What is the output of method "main" below?
public class Q1 {
private static int a = 1;
private int b;
private Q1 c = null;
public Q1() {
b = a;
a = 2*a;
}
public String toString() {
String s = "null";
if (c != null) s =
"" + c.b;
return a + " " + b
+ " " + s;
}
public void magic(int a) {
Q1 now = this;
while (now != null) {
System.out.println(a + " " + now);
now = now.c;
}
}
public static void main (String[] args) {
Q1 a = new Q1();
Q1 b = new Q1();
Q1 c = new Q1();
c = a;
a.c = b;
c.c.b++;
// draw a picture of "the world" as it exists at
THIS LINE
c.magic(7);
}
}
b) Does method
"toString()" above return a value or print a value? How --Java
willing-- would you change the code for method "toString()" to make
it do the other (print instead of return or vice versa)?
c) Define the term "class".
d) Define the term "method".
e) Explain the difference between public and private.
f) Explain the differences between static and non-static.
b) Androids Trurl and Klapaucius
perform a random walk on a grid. Both begin at square (0,0). At
each step, they independently move one square to the right and one square up or
down, e.g., from (0,0), each android will move independently to either (1,1) or
(1,-1). Trurl's probability of moving up is 60%; Klapaucius' probability
of moving is 45%.
Write a code segment to simulate 200 steps of their random walk and count how
many times they meet during their walk (how often they are standing on the same
square). Output this number to the screen. Do not include their
starting position in your count.
HINT: The expression Math.random() <= 0.4 will be true with probability
40%. Function Math.random() returns a random number strictly between 0.0
and 1.0.
0<= tens <=5 and 0<= digits <= 9
because any quantity of minutes can be converted to an MM60 quantity in the
range 0..59. Examples:
28 minutes: |
|
tens = 2, ones = 8 |
125 minutes = 5 minutes modulo 60: |
|
tens = 0, ones = 5 |
-17 minutes = 43 minutes modulo 60: |
|
tens = 4, ones = 3 |
|
|
|
|
|
|
|
|
|
|
|
|