Sample Review Exam - Solutions
Correct answers appear in blue.
Time alloted: 30'
There are six questions, each should take you 5 minutes for 12/3 points (10 points in all).
1. Turtleland
Assume the following code in a file Turtles.java
.
You compile and run this code:
public class Turtles { public static void main(String[] args) { Turtle a = new Turtle("Condor"); int x = 2; a.position(); a.jump(x, x + 2); a.position(); } } class Turtle { private int x, y; private String name; Turtle(String givenName) { name = givenName; x = 0; y = 0; } void jump(int newX, int newY) { x = newX; y = newY; System.out.println(name + " jumped to (" + x + ", " + y + ") "); } void position() { System.out.println(name + " located at (" + x + ", " + y + ") "); } }What's the output of this program? Write your answer here:
Answer: compiling
The instance method Calling Turtle.java
produces
two .class
files:
If we run Turtles.class
Turtle.class
Turtles
execution will start with its
main
method. This method creates a new object, an instance
of class Turtle
and will keep a reference to it in the
Turtle a
variable. When created, this object will set its
private String name
variable to "Condor"
and the x
and y
coordinates to
0
and 0
respectively. position()
reports the current values
of the x
and y
coordinates. Originally the
Turtle
is located at (0, 0)
. The
jump(x, x + 2)
method sets x
and y
to 2
and 4
respectively and after that it reports
the change. position()
once again we obtain the
following output:
On a real test, unless otherwise mentioned, no justification is required for
such a question (in this case simply listing the correct the output would have
been enough).
Condor located at (0, 0)
Condor jumped to (2, 4)
Condor located at (2, 4)
Note: objects of class Turtle
have a position, determined
by their x and y coordinate in the plane, and they can jump to a certain
location specified by a new pair of coordinates (the coordinates of the
new position, to which the turtle jumps to). These are atomic turtles.
2. Arrays