CPSC 124, Fall 2011
Quiz #1

Question 1. What is meant by a type in Java? List at least three of Java's primitive types.

Answer. A type specifies a set of possible values. Every variable has a type, which specifies the kind of values that can be stored in that variable. A constant such as 17 has a type, which tells what kind of value it is. An expression has a type, which tells what kind of value is computed by that expression.

The three most common primitive types in Java are int, double, and boolean. (The complete list of primitive types also includes char, long, short, byte, and float.)

Question 2. What is meant by a literal in a computer program? Give two examples of literals that could occur in a Java program. Your two examples should have different types.

Answer. A literal is a notation (that is, a sequence of character) that is used in a program to represent a constant value. For example, "Hello" is a literal of type String, that represents a constant string value consisting of the sequence of characters H-e-l-l-o. (The quotation marks are part of the literal, but they are not part of the value that is represented!) The literals of type boolean are true and false. Literals of type char are written using single quotation marks, such as 'A', '*', and '\t'17 is a literal of type int, and 17L is a literal of type long. (Actually, 17 is a literal of type byte, since it can be represented using 8 bits; however, that's a technicality that rarely makes a difference.)

Question 3. Complete the following program so that it does the following: Ask the user to enter his or her name. Use TextIO.getln() to read the user's response. Greet the user by name (for example, "Hello, Fred.").

Answer.

public class Area {
   public static void main(String[] args) {
      String name;
      System.out.print("Please enter your name: ");
      name = TextIO.getln();
      System.out.println("Hello, " + name);
   }
}

Question 4. The standard Java function Math.sqrt computes the square root of a number. Complete the following program so that it will ask the user to type in a number, then read the user's response, then print out the square root of the user's number. You can use TextIO to read the user's input.

Answer.

public class Greet {
   public static void main(String[] args) {
      double number, answer;
      System.out.print("Please enter a number: ");
      number = TextIO.getlnDouble();
      answer = Math.sqrt(number);
      System.out.println("The square root of " + number + " is " + answer);
   }
}