1. What is meant by the type of a variable? Give three examples of types in Java.
Answer: The type of a variable tells what kind of data that variable will hold. It tells how many bits the variable will hold and how those bits are to be interpreted. Three types in Java are int, double, and String. (An int variable, for example, holds 32 bits, and those bits are interpreted as a 32-bit integer in the binary number system.)
2. It is legal to call System.out.println() with no parameter in the parentheses. It is not legal to call System.out.print() with no parameter in the parentheses. Explain the difference between "print" and "{println" in these statements, and explain why {\tt System.out.print()}, without a parameter, doesn't make sense.
Answer: System.out.println(x) and System.out.print(x) both output the value of x. The difference is that when println is used, a line feed (or "end-of-line") is output after the value of x, so that subsequent output will start on the next line. With print, only the value of x is output, and subsequent output will follow x on the same line. System.out.println(), with nothing in the parentheses, makes sense because it still has something to do: it will output a line feed. System.out.print() does not make sense as as statement because it has nothing at all to do; it would not produce any output at all. (In fact, System.out.print(), with no parameter, is illegal and will be reported as an error by the compiler.)
3. The area of a circle of radius r is given by 3.14159*r2. Complete the following program so that it computes and prints the area of a circle of radius 17.42. The program should declare two variables named radius and area of type double; assign the value 17.42 to radius; and then compute and print the area.
Answer:
public class Area { public static void main(String[] args) { double radius; double area; radius = 17.42; area = 3.14159 * radius * radius; System.out.println( "The area of a circle of radius " + radius + " is " + area ); } }
4. Complete the following program so that it will ask for the user's name, read the user's response, and then greet the user by name (for example: Hello, Fred). You can use TextIO to read the user's input.
Answer:
public class Greet { public static void main(String[] args) { String name; System.out.print( "Hi, what's your name? " ); name = TextIO.getln(); System.out.println( "Hello, " + name ); } }