CPSC 124, Spring 2013
Sample Answers to Quiz #2

Question 1. What does it mean to declare a variable? Give an example.

Answer. Before you can use a variable in a program, that variable must be declared. When you declare a variable, you tell the computer that the variable exists, and you say what type of values can be assigned to the variable. Here are three examples:

int i;
String first, last;
double interestRate;

Question 2. If str is a variable of type String, and if the value of the variable is "eschew", what is the value of str.charAt(5)? Why?

Answer. The value of str.charAt(5) is the char 'w'. This is character number 5 in the string "eschew". (Characters are numbered starting from zero, not from one, so character number 5 is what we might ordinarily call the sixth character.)

Question 3. List three of Java's primitive types.

Answer. int, double, and boolean

(A type specifies some particular kind of data. Java has primitive types and object types. There are exactly 8 primitive types, and there is no way to create new ones. The full list of primitive types is: byte, short, int, long, float, double, char, and boolean. Note that String is an object type, not a primitive type. This is what allows strings to have subroutines, such as str.charAt().)

Question 4. Complete the following program so that it does the following: Ask the user to enter an integer, and read the user's response. Then tell the user the remainder when their number is divided by 17.


public class SillyIO {

    public static void main(String[] args) {
        int userNumber;  // The number that is to be entered by the user.
        int remainder;   // The answer, which will be output to the user.
        System.out.print("What is your number? ");
        userNumber = TextIO.getlnInt();
        remainder = userNumber % 17;
        System.out.println("The remainder is " + remainder);