1. Explain clearly and completely the meaning of the following statement:
double x = 1.618;
Answer: This statement combines two things. First of all, it declares a variable, named x and of type double. Then it initializes the variable by assigning the value 1.618 to it. That is, this statement does the same thing as the two statements double x; and x = 1.618;.
2. (a) Suppose that you want to define a named constant with name ROWS and with value 40. What statement would you write in order to create this constant?
(b) Briefly explain why you might want to define such a constant.
Answer:
(a) public static final int ROWS = 40;
(b) There are several reasons to define named constants. First of all, having a meaningful name for the constant can make a program easier to understand. Making the variable "final" means that you can be sure that your program won't accidently change the value of the variable. It also makes it easy to change the value of the constant between program runs, since you only have to change the one line where the constant is declared; if you used a numeric constant throughout the program instead of a name, then in order to change the value, you would have to track down every relevant occurrence of that number in the program and change it.
3. "A variable in Java can never hold an object." Explain this statement. (Where is the object if it's not in the variable? When working with objects, what can a variable hold?)
Answer: In Java, a variable holds a pointer (also known as a reference) to an object, not the object itself. The object is stored elsewhere, in a part of memory that is known as the heap. The "pointer" that is stored in the variable is actually just the address of the location in memory where the object can be found, which allows the computer to find the object. The pointer is often visualized as an arrow that leads from the variable to the object; when the computer needs to access the object, it follows this arrow.
4. Suppose that a class named Student is defined as shown here. Write a code segment that will (1) Declare a variable of type Student; (2) Create an object of type Student; and (3) Set the name in the student object to be "Jane Doe" and its id to be 10109999.
public class Student { public String name; public int id; }
Answer:
Student stu; // Declare a variable named stu, of type Student. stu = new Student(); // Create the object, and set stu to refer to it. stu.name = "Jane Doe"; // Set the name variable in the object. stu.id = 10109999; // Set the id variable in the object.