Introduction to Java Programming, Eighth Edition, Y. Daniel Liang

Chapter 2 Elementary Programming


Section 2.3 Console Input Using the Scanner Class
1  Suppose a Scanner object is created as follows:

Scanner input = new Scanner(System.in);

What method do you use to read an int value?


A. input.nextInt();
B. input.nextInteger();
C. input.int();
D. input.integer();

2  The following code fragment reads in two numbers:

Scanner input = new Scanner(System.in);
int i = input.nextInt();
double d = input.nextDouble();

What are the correct ways to enter these two numbers?


A. Enter an integer, a space, a double value, and then the Enter key.
B. Enter an integer, two spaces, a double value, and then the Enter key.
C. Enter an integer, an Enter key, a double value, and then the Enter key.
D. Enter a numeric value with a decimal point, a space, an integer, and then the Enter key.

3  If you enter 1 2 3, when you run this program, what will be the output?

import java.util.Scanner;

public class Test1 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter three numbers: ");
    double number1 = input.nextDouble();
    double number2 = input.nextDouble();
    double number3 = input.nextDouble();

    // Compute average
    double average = (number1 + number2 + number3) / 3;

    // Display result
    System.out.println(average);
  }
}


A. 1.0
B. 2.0
C. 3.0
D. 4.0

4  What is the exact output of the following code?

  double area = 3.5;
  System.out.print("area");
  System.out.print(area);


A. 3.53.5
B. 3.5 3.5
C. area3.5
D. area 3.5

Section 2.4 Identifiers
5  Every letter in a Java keyword is in lowercase?

A. true
B. false

6  Which of the following is a valid identifier?

A. $343
B. class
C. 9X
D. 8+9
E. radius

Section 2.5 Variables
7  Which of the following are correct names for variables according to Java naming conventions?

A. radius
B. Radius
C. RADIUS
D. findArea
E. FindArea

8  Which of the following are correct ways to declare variables?

A. int length; int width;
B. int length, width;
C. int length; width;
D. int length, int width;

Section 2.6 Assignment Statements and Assignment Expressions
9  ____________ is the Java assignment operator.

A. ==
B. :=
C. =
D. =:

10  To assign a value 1 to variable x, you write

A. 1 = x;
B. x = 1;
C. x := 1;
D. 1 := x;
E. x == 1;