CPSC 124, Fall 2017: Sample Answers to Quiz #5

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. What does null represent in Java?

Answer. The value null can be assigned to an object variable (that is, a variable that can refer to an object). It is a special value that can be stored in an object variable to mean that the variable does not point to any object; null is a "pointer" value that does not point to anything.

Question 2. Explain why the test   if (answer == "yes")   can be false even when ans is a variable of type String whose value is "yes".

Answer. The test   if (answer == "yes")   is comparing objects. It is true only if the two objects are the same. The fact that the two objects hold the same value (the characters a-n-s) does not necessarily make them the same object, so the "==" test will not necessarily say they are equal.

(Strings in Java are objects. That means that a String variable does not actually store a string; it stores a pointer to an object that holds the string. Thus, ans holds a pointer to an object that contains the string "ans". Similarly, the literal "yes" actually represents an object that holds the string "yes". The "==" operator tests whether these two objects are the same, not whether they hold the same data. To test that, you would use   if (answer.equals("yes")).)

Question 3. Explain the meaning of "final" in the declaration:

       public final static int MAX_SIZE = 1000;

Answer. When the "final" modifier is included in a variable declaration, the value of the variable cannot be changed while the program is running; it keeps its initial value for the whole run of the program, and it is impossible to assign a new value to it. In this case, the value of MAX_SIZE will always be 1000, unless the program source code is modified and the program is re-compiled.

Question 4. The picture below shows three variables (pt1, pt2, and pt3) pointing to two objects. The variables are of type Point, where Point is the class shown on the left. Complete the code segment to make it create the situation shown in the picture. The variables are already declared. You need to add code to create objects containing data as shown, and give pt1, pt2, and pt3 the values illustrated in the picture.

public class Point {
    int x;
    int y;
}

Point pt1, pt2, pt3;

Answer.

Point pt1, pt2, pt3;
pt1 = new Point();
pt1.x = 15;
pt1.y = 3;
pt2 = p1;
pt3 = new Point();
pt3.x = 17;
pt3.y = 42;