11/21/24, 1:32 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at
[Link]
Chapter 1 Introduction to Computers,
Programs, and Java
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 1.2 What is a Computer?
1.1 ________ is the physical aspect of the computer
that can be seen.
A. Hardware
B. Software
C. Operating system
D. Application program
Your answer is correct
[Link] 1/15
11/21/24, 1:32 AM Introduction to Java Programming
1.2 __________ is the brain of a computer.
A. Hardware
B. CPU
C. Memory
D. Disk
Your answer A is incorrect
The correct answer is B
1.3 The speed of the CPU may be measured in
__________.
A. megabytes
B. gigabytes
C. megahertz
D. gigahertz
Your answer A is incorrect
The correct answer is CD
Explanation: 1 megahertz equals 1 million pulses
per second and 1 gigahertz is 1000 megahertz.
1.4 Why do computers use zeros and ones?
A. because combinations of zeros
and ones can represent any
numbers and characters.
B. because digital devices have two
stable states and it is natural
to use one state for 0 and the
other for 1.
C. because binary numbers are
simplest.
D. because binary numbers are the
bases upon which all other number
systems are built.
Your answer A is incorrect
[Link] 2/15
11/21/24, 1:32 AM Introduction to Java Programming
The correct answer is B
1.5 One byte has ________ bits.
A. 4
B. 8
C. 12
D. 16
Your answer A is incorrect
The correct answer is B
1.6 Which of the following is not permanent storage
devices?
A. floppy disk
B. hard disk
C. flash stick
D. CD-ROM
E. main memory
Your answer A is incorrect
The correct answer is E
Explanation: Disks and CD are used to store data
permanently. Data in memory is lost after the
power is turned off.
1.7 ____________ is a device to connect a computer
to a local area network (LAN).
A. Regular modem
B. DSL
C. Cable modem
D. NIC
Your answer A is incorrect
The correct answer is D
Explanation: Network Interface Card (NIC) is a
device to connect a computer to a local area
[Link] 3/15
11/21/24, 1:32 AM Introduction to Java Programming
network.
Section 1.3 Program Languages
1.8 ____________ are instructions to the computer.
A. Hardware
B. Software
C. Programs
D. Keyboards
Your answer A is incorrect
The correct answer is BC
1.9 Computer can execute the code in
____________.
A. machine language
B. assembly language
C. high-level language
D. none of the above
Your answer is correct
1.10 ___________ translates high-level language
program into machine language program.
A. An assembler
B. A compiler
C. CPU
D. The operating system
Your answer A is incorrect
The correct answer is B
Section 1.4 Operating Systems
1.11 ____________ is an operating system.
A. Java
B. C++
[Link] 4/15
11/21/24, 1:32 AM Introduction to Java Programming
C. Windows
D. Visual Basic
E. Ada
Your answer A is incorrect
The correct answer is C
1.12 _____________ is a program that runs on a
computer to manage and control a computer's
activities.
A. Operating system
B. Java
C. Modem
D. Interpreter
E. Compiler
Your answer is correct
Section 1.5 Java, World Wide Web, and Beyond
1.13 Java was developed by ____________.
A. Sun Microsystems
B. Microsoft
C. Apple
D. IBM
E. Cisco Systems
Your answer is correct
1.14 Due to security reasons, Java ___________
cannot run from a Web browser in the new version
of Java.
A. applications
B. applets
C. servlets
D. Micro Edition programs
Your answer A is incorrect
[Link] 5/15
11/21/24, 1:32 AM Introduction to Java Programming
The correct answer is B
1.15 ________ is not an object-oriented
programming language.
A. Java
B. C++
C. C
D. C#
E. Python
Your answer A is incorrect
The correct answer is C
1.16 ________ is interpreted.
A. Java
B. C++
C. C
D. Ada
E. Pascal
Your answer is correct
1.17 ________ is architecture-neutral.
A. Java
B. C++
C. C
D. Ada
E. Pascal
Your answer is correct
Section 1.6 The Java Language Specification, API,
JDK, and IDE
1.18 ________ is a technical definition of the
language that includes the syntax and semantics of
the Java programming language.
[Link] 6/15
11/21/24, 1:32 AM Introduction to Java Programming
A. Java language specification
B. Java API
C. Java JDK
D. Java IDE
Your answer is correct
1.19 ________ contains predefined classes and
interfaces for developing Java programs.
A. Java language specification
B. Java API
C. Java JDK
D. Java IDE
Your answer A is incorrect
The correct answer is B
1.20 ________ consists of a set of separate
programs for developing and testing Java
programs, each of which is invoked from a
command line.
A. Java language specification
B. Java API
C. Java JDK
D. Java IDE
Your answer A is incorrect
The correct answer is C
1.21 ________ provides an integrated development
environment (IDE) for rapidly developing Java
programs. Editing, compiling, building,
debugging, and online help are integrated in one
graphical user interface.
A. Java language specification
B. Java API
C. Java JDK
[Link] 7/15
11/21/24, 1:32 AM Introduction to Java Programming
D. Java IDE
Your answer A is incorrect
The correct answer is D
Section 1.7 A Simple Java Program
1.22 The main method header is written as:
A. public static void main(string[]
args)
B. public static void Main(String[]
args)
C. public static void main(String[]
args)
D. public static main(String[]
args)
E. public void main(String[] args)
Your answer A is incorrect
The correct answer is C
1.23 Which of the following statements is correct?
A. Every line in a program must end
with a semicolon.
B. Every statement in a program
must end with a semicolon.
C. Every comment line must end with
a semicolon.
D. Every method must end with a
semicolon.
E. Every class must end with a
semicolon.
Your answer A is incorrect
The correct answer is B
[Link] 8/15
11/21/24, 1:32 AM Introduction to Java Programming
1.24 Which of the following statements is correct to
display Welcome to Java on the console?
A. [Link]('Welcome to
Java');
B. [Link]("Welcome to
Java");
C. [Link]('Welcome to
Java');
D. [Link]('Welcome to
Java");
E. [Link]("Welcome to
Java');
Your answer A is incorrect
The correct answer is B
Section 1.8 Creating, Compiling, and Executing a
Java Program
1.25 The JDK command to compile a class in the
file [Link] is
A. java Test
B. java [Link]
C. javac [Link]
D. javac Test
E. JAVAC [Link]
Your answer A is incorrect
The correct answer is C
1.26 Which JDK command is correct to run a Java
application in [Link]?
A. java ByteCode
B. java [Link]
C. javac [Link]
D. javac ByteCode
E. JAVAC ByteCode
[Link] 9/15
11/21/24, 1:32 AM Introduction to Java Programming
Your answer is correct
1.27 Java compiler translates Java source code into
_________.
A. Java bytecode
B. machine code
C. assembly code
D. another high-level language code
Your answer is correct
1.28 _________ is a software that interprets Java
bytecode.
A. Java virtual machine
B. Java compiler
C. Java debugger
D. Java API
Your answer is correct
1.29 Suppose you define a Java class as follows, the
source code should be stored in a file named
_________.
public class Test {
}
A. [Link]
B. [Link]
C. [Link]
D. [Link]
E. Any name with extension .java
Your answer A is incorrect
The correct answer is D
1.30 The extension name of a Java bytecode file is
[Link] 10/15
11/21/24, 1:32 AM Introduction to Java Programming
A. .java
B. .obj
C. .class
D. .exe
Your answer A is incorrect
The correct answer is C
1.31 The extension name of a Java source code file
is
A. .java
B. .obj
C. .class
D. .exe
Your answer is correct
1.32 Which of the following lines is not a Java
comment?
A. /** comments */
B. // comments
C. -- comments
D. /* comments */
E. ** comments **
Your answer A is incorrect
The correct answer is CE
1.33 Which of the following are the reserved
words?
A. public
B. static
C. void
D. class
Your answer A is incorrect
The correct answer is ABCD
[Link] 11/15
11/21/24, 1:32 AM Introduction to Java Programming
1.34 Every statement in Java ends with ________.
A. a semicolon (;)
B. a comma (,)
C. a period (.)
D. an asterisk (*)
Your answer is correct
1.35 A block is enclosed inside __________.
A. parentheses
B. braces
C. brackets
D. quotes
Your answer A is incorrect
The correct answer is B
Section 1.9 Programming Style and Documentation
1.36 Programming style is important, because
______________.
A. a program may not compile if it
has a bad style
B. good programming style can make
a program run faster
C. good programming style makes a
program more readable
D. good programming style helps
reduce programming errors
Your answer A is incorrect
The correct answer is CD
1.37 Analyze the following code.
I:
[Link] 12/15
11/21/24, 1:32 AM Introduction to Java Programming
public class Test {
public static void main(String[] args) {
[Link]("Welcome to
Java!");
}
}
II:
public class Test { public static void main(String[]
[Link]("Welcome to Java!"); } }
A. Both I and II can compile and
run and display Welcome to Java,
but the code in II has a better
style than I.
B. Only the code in I can compile
and run and display Welcome to
Java.
C. Only the code in II can compile
and run and display Welcome to
Java.
D. Both I and II can compile and
run and display Welcome to Java,
but the code in I has a better
style than II.
Your answer A is incorrect
The correct answer is D
1.38 Which of the following code has the best
style?
I:
public class Test {
public static void main(String[] args) {
[Link]("Welcome to
Java!");
}
}
II:
public class Test {
public static void main(String[] args)
[Link] 13/15
11/21/24, 1:32 AM Introduction to Java Programming
{
[Link]("Welcome to
Java!");
}
}
III:
public class Test {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
IV:
public class Test {
public static void main(String[] args) {
[Link]("Welcome to
Java!");
}
}
A. I
B. II
C. III
D. IV
Your answer A is incorrect
The correct answer is D
Section 1.10 Programming Errors
1.39 If a program compiles fine, but it produces
incorrect result, then the program suffers
__________.
A. a compilation error
B. a runtime error
C. a logic error
Your answer A is incorrect
The correct answer is C
[Link] 14/15
11/21/24, 1:32 AM Introduction to Java Programming
1.40 If you forget to put a closing quotation mark
on a string, what kind of error will be raised?
A. a compile error
B. a runtime error
C. a logic error
Your answer is correct
Explanation: This is a syntax error, which will be
detected by the compiler.
[Link] 15/15
11/21/24, 1:39 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at
[Link]
Chapter 2 Elementary Programming
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 2.2 Writing a Simple Program
2.1 _______ is the code with natural language
mixed with Java code.
A. Java program
B. A Java statement
C. Pseudocode
D. A flowchart diagram
Your answer A is incorrect
The correct answer is C
[Link] 1/26
11/21/24, 1:39 AM Introduction to Java Programming
2.2 What is the exact output of the following code?
double area = 3.5;
[Link]("area");
[Link](area);
A. 3.53.5
B. 3.5 3.5
C. area3.5
D. area 3.5
Your answer A is incorrect
The correct answer is C
Explanation: The first print statement prints a
string followed by the second print statement that
prints a number.
Section 2.3 Reading Input from the Console
2.3 Suppose a Scanner object is created as follows,
what method do you use to read a real number?
Scanner input = new Scanner([Link]);
A. [Link]();
B. [Link]();
C. [Link]();
D. [Link]();
Your answer is correct
Explanation: The correct method to read a real
number is nextDouble().
2.4 The following code fragment reads in two
numbers:
Scanner input = new Scanner([Link]);
int i = [Link]();
double d = [Link]();
[Link] 2/26
11/21/24, 1:39 AM Introduction to Java Programming
What is the incorrect way 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.
Your answer A is incorrect
The correct answer is D
2.5 If you enter 1 2 3, when you run this program,
what will be the output?
import [Link];
public class Test1 {
public static void main(String[] args) {
Scanner input = new
Scanner([Link]);
[Link]("Enter three numbers:
");
double number1 = [Link]();
double number2 = [Link]();
double number3 = [Link]();
// Compute average
double average = (number1 + number2 +
number3) / 3;
// Display result
[Link](average);
}
}
[Link] 3/26
11/21/24, 1:39 AM Introduction to Java Programming
A. 1.0
B. 2.0
C. 3.0
D. 4.0
Your answer A is incorrect
The correct answer is B
Explanation: (1.0 + 2.0 + 3.0) / 3 is 2.0
Section 2.4 Identifiers
2.6 Every letter in a Java keyword is in lowercase?
A. true
B. false
Your answer is correct
Explanation: It is true that the keywords in Java
are in lowercase. For example, public, static, int,
double, and void are the keywords.
2.7 Which of the following is a valid identifier?
A. $343
B. class
C. 9X
D. 8+9
E. radius
Your answer A is incorrect
The correct answer is AE
Explanation: class is a keyword, which cannot be
used as an identifier. Identifiers cannot start with
a number.
Section 2.5 Variables
2.8 Which of the following are correct names for
variables according to Java naming conventions?
[Link] 4/26
11/21/24, 1:39 AM Introduction to Java Programming
A. radius
B. Radius
C. RADIUS
D. findArea
E. FindArea
Your answer A is incorrect
The correct answer is AD
Explanation: A single-word variable is in
lowercase. In a multiple-word variable, the words
are concatenated with the first word in lowercase
and the first letter of each subsequent word in
uppercase.
2.9 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;
Your answer A is incorrect
The correct answer is AB
Explanation: Note that a semicolon ends a
statement. In B, length and width are both
declared as int.
Section 2.6 Assignment Statements and Assignment
Expressions
2.10 ____________ is the Java assignment
operator.
A. ==
B. :=
C. =
D. =:
[Link] 5/26
11/21/24, 1:39 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
2.11 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;
Your answer A is incorrect
The correct answer is B
2.12 Which of the following assignment statements
is incorrect?
A. i = j = k = 1;
B. i = 1; j = 1; k = 1;
C. i = 1 = j = 1 = k = 1;
D. i == j == k == 1;
Your answer A is incorrect
The correct answer is CD
Section 2.7 Named Constants
2.13 To declare a constant MAX_LENGTH inside
a method with value 99.98, you write
A. final MAX_LENGTH = 99.98;
B. final float MAX_LENGTH = 99.98;
C. double MAX_LENGTH = 99.98;
D. final double MAX_LENGTH =
99.98;
Your answer A is incorrect
The correct answer is D
[Link] 6/26
11/21/24, 1:39 AM Introduction to Java Programming
2.14 Which of the following is a constant,
according to Java naming conventions?
A. MAX_VALUE
B. Test
C. read
D. ReadInt
E. COUNT
Your answer A is incorrect
The correct answer is AE
Explanation: All letters in a constant are in
uppercase. In a multiple-word constant, the words
are connected using underscores.
2.15 To improve readability and maintainability,
you should declare _________ instead of using
literal values such as 3.14159.
A. variables
B. methods
C. constants
D. classes
Your answer A is incorrect
The correct answer is C
Explanation: A constant gives a literal a
descriptive name and makes the code more
readable.
Section 2.8 Naming Conventions
2.16 According to Java naming convention, which
of the following names can be variables?
A. FindArea
B. findArea
C. totalLength
D. TOTAL_LENGTH
[Link] 7/26
11/21/24, 1:39 AM Introduction to Java Programming
E. class
Your answer A is incorrect
The correct answer is BC
Explanation: The first word in a variable is in
lowercase. So B and C are correct.
Section 2.9 Numeric Data Types and
Operations Section 2.9.1 Numeric Types
2.17 Which of these data types requires the most
amount of memory?
A. long
B. int
C. short
D. byte
Your answer is correct
Explanation: long takes 8 bytes. int 4 bytes. short
2 bytes. byte 1 byte.
2.18 When assigning a literal to a variable of the
byte type, if the literal is too large to be stored as
a byte value, it _____________.
A. causes overflow
B. causes underflow
C. causes no error
D. cannot happen in Java
E. receives a compile error
Your answer A is incorrect
The correct answer is E
Explanation: For example, byte b = 23232 will
cause a compile error.
Section 2.9.3 Numeric Operators
[Link] 8/26
11/21/24, 1:39 AM Introduction to Java Programming
2.19 What is the result of 45 / 4?
A. 10
B. 11
C. 11.25
D. 12
Your answer A is incorrect
The correct answer is B
Explanation: 45 / 4 is an integer division, which
results in 11
2.20 Which of the following expression results in a
value 1?
A. 2 % 1
B. 15 % 4
C. 25 % 5
D. 37 % 6
Your answer A is incorrect
The correct answer is D
Explanation: 2 % 1 is 0, 15 % 4 is 3, 25 % 5 is 0,
and 37 % 6 is 1
2.21 25 % 1 is _____
A. 1
B. 2
C. 3
D. 4
E. 0
Your answer A is incorrect
The correct answer is E
2.22 -25 % 5 is _____
A. 1
[Link] 9/26
11/21/24, 1:39 AM Introduction to Java Programming
B. 2
C. 3
D. 4
E. 0
Your answer A is incorrect
The correct answer is E
2.23 24 % 5 is _____
A. 1
B. 2
C. 3
D. 4
E. 0
Your answer A is incorrect
The correct answer is D
2.24 -24 % 5 is _____
A. -1
B. -2
C. -3
D. -4
E. 0
Your answer A is incorrect
The correct answer is D
2.25 -24 % -5 is _____
A. 3
B. -3
C. 4
D. -4
E. 0
[Link] 10/26
11/21/24, 1:39 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is D
Section 2.9.4 Exponent Operations
2.26 How do you write 2.5 ^ 3.1 in Java?
A. 2.5 * 3.1
B. [Link](2.5, 3.1)
C. [Link](3.1, 2.5)
D. 2.5 ** 3.1
E. 3.1 ** 2.5
Your answer A is incorrect
The correct answer is B
2.27 [Link](2, 3) returns __________.
A. 9
B. 8
C. 9.0
D. 8.0
Your answer A is incorrect
The correct answer is D
Explanation: It returns a double value 8.0.
2.28 [Link](4, 1 / 2) returns __________.
A. 2
B. 2.0
C. 0
D. 1.0
E. 1
Your answer A is incorrect
The correct answer is D
Explanation: Note that 1 / 2 is 0.
[Link] 11/26
11/21/24, 1:39 AM Introduction to Java Programming
2.29 [Link](4, 1.0 / 2) returns __________.
A. 2
B. 2.0
C. 0
D. 1.0
E. 1
Your answer A is incorrect
The correct answer is B
Explanation: Note that the pow method returns a
double value, not an integer.
2.30 The __________ method returns a raised to
the power of b.
A. [Link](a, b)
B. [Link](a, b)
C. [Link](a, b)
D. [Link](b, a)
Your answer A is incorrect
The correct answer is C
Section 2.10 Numeric Literals
2.31 To declare an int variable number with initial
value 2, you write
A. int number = 2L;
B. int number = 2l;
C. int number = 2;
D. int number = 2.0;
Your answer A is incorrect
The correct answer is C
[Link] 12/26
11/21/24, 1:39 AM Introduction to Java Programming
2.32 Analyze the following code.
public class Test {
public static void main(String[] args) {
int month = 09;
[Link]("month is " +
month);
}
}
A. The program displays month is
09.
B. The program displays month is 9.
C. The program displays month is
9.0.
D. The program has a syntax error,
because 09 is an incorrect
literal value.
Your answer A is incorrect
The correct answer is D
Explanation: Any numeric literal with the prefix 0
is an octal value. But 9 is not an octal digit. An
octal digit is 0, 1, 2, 3, 4, 5, 6, or 7.
2.33 Which of the following is incorrect?
A. 1_2
B. 0.4_56
C. 1_200_229
D. _4544
Your answer A is incorrect
The correct answer is D
Explanation: You can use the digit separator _ for
integers or floating point numbers. The separator
must be placed between the digits.
2.34 Which of the following are the same as
1545.534?
[Link] 13/26
11/21/24, 1:39 AM Introduction to Java Programming
A. 1.545534e+3
B. 0.1545534e+4
C. 1545534.0e-3
D. 154553.4e-2
Your answer A is incorrect
The correct answer is ABCD
2.35 Which of the following is incorrect?
A. int x = 9;
B. long x = 9;
C. float x = 1.0;
D. double x = 1.0;
Your answer A is incorrect
The correct answer is C
Section 2.11 Evaluating Expressions and Operator
Precedence
2.36 The expression 4 + 20 / (3 - 1) * 2 is evaluated
to
A. 4
B. 20
C. 24
D. 9
E. 25
Your answer A is incorrect
The correct answer is C
Section 2.12 Case Study: Displaying the Current
Time
2.37 The [Link]() returns
________________ .
[Link] 14/26
11/21/24, 1:39 AM Introduction to Java Programming
A. the current time.
B. the current time in
milliseconds.
C. the current time in milliseconds
since midnight.
D. the current time in
milliseconds since midnight,
January 1, 1970.
E. the current time in milliseconds
since midnight, January 1, 1970
GMT (the Unix time).
Your answer A is incorrect
The correct answer is E
2.38 To obtain the current second, use _________.
A. [Link]() %
3600
B. [Link]() % 60
C. [Link]() /
1000 % 60
D. [Link]() /
1000 / 60 % 60
E. [Link]() /
1000 / 60 / 60 % 24
Your answer A is incorrect
The correct answer is C
2.39 To obtain the current minute, use _________.
A. [Link]() %
3600
B. [Link]() % 60
C. [Link]() /
1000 % 60
D. [Link]() /
1000 / 60 % 60
[Link] 15/26
11/21/24, 1:39 AM Introduction to Java Programming
E. [Link]() /
1000 / 60 / 60 % 24
Your answer A is incorrect
The correct answer is D
2.40 To obtain the current hour in UTC, use
_________.
A. [Link]() %
3600
B. [Link]() % 60
C. [Link]() /
1000 % 60
D. [Link]() /
1000 / 60 % 60
E. [Link]() /
1000 / 60 / 60 % 24
Your answer A is incorrect
The correct answer is E
Section 2.13 Augmented Assignment Operators
2.41 To add a value 1 to variable x, you write
A. 1 + x = x;
B. x += 1;
C. x := 1;
D. x = x + 1;
E. x = 1 + x;
Your answer A is incorrect
The correct answer is BDE
2.42 To add number to sum, you write (Note: Java
is case-sensitive)
A. number += sum;
[Link] 16/26
11/21/24, 1:39 AM Introduction to Java Programming
B. number = sum + number;
C. sum = Number + sum;
D. sum += number;
E. sum = sum + number;
Your answer A is incorrect
The correct answer is DE
2.43 Suppose x is 1. What is x after x += 2?
A. 0
B. 1
C. 2
D. 3
E. 4
Your answer A is incorrect
The correct answer is D
2.44 Suppose x is 1. What is x after x -= 1?
A. 0
B. 1
C. 2
D. -1
E. -2
Your answer is correct
2.45 What is x after the following statements?
int x = 2;
int y = 1;
x *= y + 1;
A. x is 1.
B. x is 2.
C. x is 3.
D. x is 4.
[Link] 17/26
11/21/24, 1:39 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is D
Explanation: (y + 1) is executed first and its result
is multiplied with x and assigned to x.
2.46 What is x after the following statements?
int x = 1;
x *= x + 1;
A. x is 1.
B. x is 2.
C. x is 3.
D. x is 4.
Your answer A is incorrect
The correct answer is B
2.47 Which of the following statements are the
same?
(A) x -= x + 4
(B) x = x + 4 - x
(C) x = x - (x + 4)
A. (A) and (B) are the same
B. (A) and (C) are the same
C. (B) and (C) are the same
D. (A), (B), and (C) are the same
Your answer A is incorrect
The correct answer is B
Section 2.14 Increment and Decrement Operators
2.48 Are the following four statements equivalent?
number += 1;
number = number + 1;
[Link] 18/26
11/21/24, 1:39 AM Introduction to Java Programming
number++;
++number;
A. Yes
B. No
Your answer is correct
2.49 What is i printed?
public class Test {
public static void main(String[] args) {
int j = 0;
int i = ++j + j * 5;
[Link]("What is i? " + i);
}
}
A. 0
B. 1
C. 5
D. 6
Your answer A is incorrect
The correct answer is D
Explanation: Operands are evaluated from left to
right in Java. The left-hand operand of a binary
operator is evaluated before any part of the right-
hand operand is evaluated. This rule takes
precedence over any other rules that govern
expressions. Therefore, ++j is evaluated first, and
j is now 1. Then j * 5 is evaluated, returns 5. So, i
is 6.
2.50 What is i printed in the following code?
public class Test {
public static void main(String[] args) {
int j = 0;
int i = j++ + j * 5;
[Link]("What is i? " + i);
[Link] 19/26
11/21/24, 1:39 AM Introduction to Java Programming
}
}
A. 0
B. 1
C. 5
D. 6
Your answer A is incorrect
The correct answer is C
Explanation: Operands are evaluated from left to
right in Java. The left-hand operand of a binary
operator is evaluated before any part of the right-
hand operand is evaluated. This rule takes
precedence over any other rules that govern
expressions. Therefore, j++ is evaluated first. j is
now 1. Since j++ is postincrement, the old value
of j is returned for j++. So j++ + j * 5 equals 0 + 1
* 5. So, the result is 5.
2.51 What is y displayed in the following code?
public class Test {
public static void main(String[] args) {
int x = 1;
int y = x++ + x;
[Link]("y is " + y);
}
}
A. y is 1.
B. y is 2.
C. y is 3.
D. y is 4.
Your answer A is incorrect
The correct answer is C
Explanation: When evaluating x++ + x, x++ is
evaluated first, which does two things: 1. returns
1 since it is post-increment. x becomes 2.
Therefore y is 1 + 2.
[Link] 20/26
11/21/24, 1:39 AM Introduction to Java Programming
2.52 What is y displayed?
public class Test {
public static void main(String[] args) {
int x = 1;
int y = x + x++;
[Link]("y is " + y);
}
}
A. y is 1.
B. y is 2.
C. y is 3.
D. y is 4.
Your answer A is incorrect
The correct answer is B
Explanation: When evaluating x + x++, x is
evaluated first, which is 1. X++ returns 1 since it
is post-increment and 2. Therefore y is 1 + 1.
Section 2.15 Numeric Type Conversions
2.53 To assign a double variable d to a float
variable x, you write
A. x = (long)d
B. x = (int)d;
C. x = d;
D. x = (float)d;
Your answer A is incorrect
The correct answer is D
2.54 Which of the following expressions will yield
0.5?
A. 1 / 2
B. 1.0 / 2
C. (double) (1 / 2)
[Link] 21/26
11/21/24, 1:39 AM Introduction to Java Programming
D. (double) 1 / 2
E. 1 / 2.0
Your answer A is incorrect
The correct answer is BDE
Explanation: 1 / 2 is an integer division, which
results in 0.
2.55 What is the output of the following code:
double x = 5.5;
int y = (int)x;
[Link]("x is " + x + " and y is " + y);
A. x is 5 and y is 6
B. x is 6.0 and y is 6.0
C. x is 6 and y is 6
D. x is 5.5 and y is 5
E. x is 5.5 and y is 5.0
Your answer A is incorrect
The correct answer is D
Explanation: The value is x is not changed after
the casting.
2.56 Which of the following assignment statements
is illegal?
A. float f = -34;
B. int t = 23;
C. short s = 10;
D. int t = (int)false;
E. int t = 4.5;
Your answer A is incorrect
The correct answer is DE
2.57 What is the value of (double)5/2?
[Link] 22/26
11/21/24, 1:39 AM Introduction to Java Programming
A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0
Your answer A is incorrect
The correct answer is B
2.58 What is the value of (double)(5/2)?
A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0
Your answer A is incorrect
The correct answer is D
2.59 Which of the following expression results in
45.37?
A. (int)(45.378 * 100) / 100
B. (int)(45.378 * 100) / 100.0
C. (int)(45.378 * 100 / 100)
D. (int)(45.378) * 100 / 100.0
Your answer A is incorrect
The correct answer is B
2.60 The expression (int)(76.0252175 * 100) / 100
evaluates to _________.
A. 76.02
B. 76
C. 76.0252175
D. 76.03
[Link] 23/26
11/21/24, 1:39 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
Explanation: In order to obtain 76.02, you have
divide 100.0.
2.61 If you attempt to add an int, a byte, a long, and
a double, the result will be a(n) __________
value.
A. byte
B. int
C. long
D. double
Your answer A is incorrect
The correct answer is D
Section 2.16 Software Life Cycle
2.62 _____________ is a formal process that seeks
to understand the problem and document in detail
what the software system needs to do.
A. Requirements specification
B. Analysis
C. Design
D. Implementation
E. Testing
Your answer is correct
2.63 _____________ seeks to analyze the data flow
and to identify the system?s input and output.
When you do analysis, it helps to identify what
the output is first, and then figure out what input
data you need in order to produce the output.
A. Requirements specification
B. Analysis
[Link] 24/26
11/21/24, 1:39 AM Introduction to Java Programming
C. Design
D. Implementation
E. Testing
Your answer A is incorrect
The correct answer is B
Section 2.18 Common Errors and Pitfalls
2.64 Analyze the following code:
public class Test {
public static void main(String[] args) {
int n = 10000 * 10000 * 10000;
[Link]("n is " + n);
}
}
A. The program displays n is
1000000000000.
B. The result of 10000 * 10000 *
10000 is too large to be stored
in an int variable n. This causes
an overflow and the program is
aborted.
C. The result of 10000 * 10000 *
10000 is too large to be stored
in an int variable n. This causes
an overflow and the program
continues to execute because Java
does not report errors on
overflow.
D. The result of 10000 * 10000 *
10000 is too large to be stored
in an int variable n. This causes
an underflow and the program is
aborted.
E. The result of 10000 * 10000 *
10000 is too large to be stored
in an int variable n. This causes
an underflow and the program
[Link] 25/26
11/21/24, 1:39 AM Introduction to Java Programming
continues to execute because Java
does not report errors on
underflow.
Your answer A is incorrect
The correct answer is C
[Link] 26/26
11/21/24, 1:43 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of
additional quiz is available for instructors using Quiz
Generator from the Instructor's Resource Website. Videos for
Java, Python, and C++ can be found at
[Link]
Chapter 3 Selections
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book
and edition you are using. Thanks!
Section 3.2 boolean Data Type
3.1 The "less than or equal to" comparison
operator in Java is __________.
A. <
B. <=
C. =<
D. <<
E. !=
[Link] 1/24
11/21/24, 1:43 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
Explanation: It reads less than or equal to. So
write the less than symbol before the equal
sign. Note that there is no space separating the
two symbols.
3.2 The equal comparison operator in Java is
__________.
A. <>
B. !=
C. ==
D. ^=
Your answer A is incorrect
The correct answer is C
Explanation: Note that there is no space
separating the double equal signs.
3.3 What is 1 + 1 + 1 + 1 + 1 == 5?
A. true
B. false
C. There is no guarantee that 1
+ 1 + 1 + 1 + 1 == 5 is true.
Your answer is correct
Explanation: These are all integers. Integer
arithmetic is accurate.
3.4 What is 1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 == 0.5?
A. true
B. false
[Link] 2/24
11/21/24, 1:43 AM Introduction to Java Programming
C. There is no guarantee that 1
- 0.1 - 0.1 - 0.1 - 0.1 - 0.1
== 0.5 is true.
Your answer A is incorrect
The correct answer is C
Explanation: This epression involves floating-
point number. Floating-point numbers are
approximated. The correct answer is C.
3.5 In Java, the word true is ________.
A. a Java keyword
B. a Boolean literal
C. same as value 1
D. same as value 0
Your answer A is incorrect
The correct answer is B
Explanation: true is a Boolean literal just like
integer literal 10.
Section 3.3 if Statements
3.6 Which of the following code displays the area
of a circle if the radius is positive?
A. if (radius != 0)
[Link](radius *
radius * 3.14159);
B. if (radius >= 0)
[Link](radius *
radius * 3.14159);
C. if (radius > 0)
[Link](radius *
radius * 3.14159);
[Link] 3/24
11/21/24, 1:43 AM Introduction to Java Programming
D. if (radius <= 0)
[Link](radius *
radius * 3.14159);
Your answer A is incorrect
The correct answer is C
Explanation: Positive means > 0.
3.7 What is the output of the following code?
int x = 0;
if (x < 4) {
x = x + 1;
}
[Link]("x is " + x);
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
Your answer A is incorrect
The correct answer is B
Explanation: Since x is 0 before the if
statement, x < 4 is true, x becomes 1 after the
statement x = x + 1. The correct answer is B.
Section 3.4 Two-Way if-else Statements
3.8 Suppose income is 4001, what is the output
of the following code?
if (income > 3000) {
[Link]("Income is greater
than 3000");
}
else if (income > 4000) {
[Link]("Income is greater
[Link] 4/24
11/21/24, 1:43 AM Introduction to Java Programming
than 4000");
}
A. no output
B. Income is greater than 3000
C. Income is greater than 3000
followed by Income is greater
than 4000
D. Income is greater than 4000
E. Income is greater than 4000
followed by Income is greater
than 3000
Your answer A is incorrect
The correct answer is B
Explanation: Since income is 4001, the
condition (income > 3000) is true. So statement
for the true case is executed.
Section 3.5 Nested if and Multi-Way if-else
Statements
3.9 The following code displays ___________.
double temperature = 50;
if (temperature >= 100)
[Link]("too hot");
else if (temperature <= 40)
[Link]("too cold");
else
[Link]("just right");
A. too hot
B. too cold
C. just right
D. too hot too cold just right
Your answer A is incorrect
The correct answer is C
[Link] 5/24
11/21/24, 1:43 AM Introduction to Java Programming
Explanation: The statement first test if
(temperature >= 100). It is false. Then it tests if
(temperature <= 4). It is false. So, it falls to the
last else clause. The correct answer is C.
Section 3.6 Common Errors and Pitfalls
3.10 Suppose x = 1, y = -1, and z = 1. What is
the output of the following statement? (Please
indent the statement correctly first.)
if (x > 0)
if (y > 0)
[Link]("x > 0 and y >
0");
else if (z > 0)
[Link]("x < 0 and z >
0");
A. x > 0 and y > 0;
B. x < 0 and z > 0;
C. x < 0 and z < 0;
D. no output.
Your answer A is incorrect
The correct answer is B
Explanation: You may copy the code to an IDE
such as NetBeans or Eclipse and reformat it to
see how it is correctly indented. The else clause
matches the most recent if clause. So, it
actually displays x < 0 and z > 0.
3.11 Analyze the following code:
boolean even = false;
if (even = true) {
[Link]("It is even");
}
[Link] 6/24
11/21/24, 1:43 AM Introduction to Java Programming
A. The program has a compile
error.
B. The program has a runtime
error.
C. The program runs fine, but
displays nothing.
D. The program runs fine and
displays It is even.
Your answer A is incorrect
The correct answer is D
Explanation: It is a common mistake to use the
= operator in the condition test. What happens
is that true is assigned to even when you write
even = true. So even is true. The program
compiles and runs fine and displays 'It is even'.
3.12 Suppose isPrime is a boolean variable,
which of the following is the correct and best
statement for testing if isPrime is true?
A. if (isPrime = true)
B. if (isPrime == true)
C. if (isPrime)
D. if (!isPrime = false)
E. if (!isPrime == false)
Your answer A is incorrect
The correct answer is C
Explanation: A and D are incorrect. B, C, and E
are correct. But C is the simplest and thus the
best.
3.13 Analyze the following code.
boolean even = false;
if (even) {
[Link] 7/24
11/21/24, 1:43 AM Introduction to Java Programming
[Link]("It is even!");
}
A. The code displays It is even!
B. The code displays nothing.
C. The code is wrong. You should
replace if (even) with if
(even == true).
D. The code is wrong. You should
replace if (even) with if
(even = true).
Your answer A is incorrect
The correct answer is B
Explanation: Since even is false, the if
statement body is not executed. So, the correct
answer is B.
3.14 Analyze the following code:
Code 1:
int number = 45;
boolean even;
if (number % 2 == 0)
even = true;
else
even = false;
Code 2:
int number = 45;
boolean even = (number % 2 == 0);
A. Code 1 has compile errors.
B. Code 2 has compile errors.
C. Both Code 1 and Code 2 have
compile errors.
D. Both Code 1 and Code 2 are
correct, but Code 2 is better.
[Link] 8/24
11/21/24, 1:43 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is D
Explanation: Both Code 1 and Code 2 are
correct. Clearly Code 2 is shorter and better.
Section 3.7 Generating Random Numbers
3.15 Which of the following is a possible output
from invoking [Link]()?
A. 3.43
B. 0.5
C. 0.0
D. 1.0
Your answer A is incorrect
The correct answer is BC
Explanation: [Link]() returns a real
value between 0.0 and 1.0, excluding 1.0.
3.16 What is the output from
[Link]((int)[Link]() * 4)?
A. 0
B. 1
C. 2
D. 3
E. 4
Your answer is correct
Explanation: Casting is performed before the *
operator in (int)[Link]() * 4. So, it
returns 0.
3.17 What is the possible output from
[Link]((int)([Link]() * 4))?
[Link] 9/24
11/21/24, 1:43 AM Introduction to Java Programming
A. 0
B. 1
C. 2
D. 3
E. 4
Your answer A is incorrect
The correct answer is ABCD
Explanation: [Link]() returns a real
value between 0.0 and 1.0, excluding 1.0.
[Link]() * 4 yields a real value between
0.0 and 4.0, excluding 4.0. After casting, the
resulting integer may be 0, 1, 2, or 3.
Section 3.8 Case Study: Computing Body Mass
Index
3.18 Suppose you write the code to display
"Cannot get a driver's license" if age is less
than 16 and "Can get a driver's license" if age
is greater than or equal to 16. Which of the
following code is correct?
I:
if (age < 16)
[Link]("Cannot get a
driver's license");
if (age >= 16)
[Link]("Can get a driver's
license");
II:
if (age < 16)
[Link]("Cannot get a
driver's license");
else
[Link]("Can get a driver's
license");
III:
[Link] 10/24
11/21/24, 1:43 AM Introduction to Java Programming
if (age < 16)
[Link]("Cannot get a
driver's license");
else if (age >= 16)
[Link]("Can get a driver's
license");
IV:
if (age < 16)
[Link]("Cannot get a
driver's license");
else if (age > 16)
[Link]("Can get a driver's
license");
else if (age == 16)
[Link]("Can get a driver's
license");
A. I
B. II
C. III
D. IV
Your answer A is incorrect
The correct answer is ABCD
Explanation: All the statements are correct. II
is the best.
3.19 Suppose you write the code to display
"Cannot get a driver's license" if age is less
than 16 and "Can get a driver's license" if age
is greater than or equal to 16. Which of the
following code is the best?
I:
if (age < 16)
[Link]("Cannot get a
driver's license");
if (age >= 16)
[Link]("Can get a driver's
license");
[Link] 11/24
11/21/24, 1:43 AM Introduction to Java Programming
II:
if (age < 16)
[Link]("Cannot get a
driver's license");
else
[Link]("Can get a driver's
license");
III:
if (age < 16)
[Link]("Cannot get a
driver's license");
else if (age >= 16)
[Link]("Can get a driver's
license");
IV:
if (age < 16)
[Link]("Cannot get a
driver's license");
else if (age > 16)
[Link]("Can get a driver's
license");
else if (age == 16)
[Link]("Can get a driver's
license");
A. I
B. II
C. III
D. IV
Your answer A is incorrect
The correct answer is B
Explanation: All the statements are correct. II
is the best.
Section 3.9 Case Study: Computing Taxes
3.20 The __________ method immediately
terminates the program.
[Link] 12/24
11/21/24, 1:43 AM Introduction to Java Programming
A. [Link](0);
B. [Link](0);
C. [Link](0);
D. [Link](0);
E. [Link](0);
Your answer A is incorrect
The correct answer is C
Explanation: [Link](0) method can be
used to terminate a program.
Section 3.10 Logical Operators
3.21 Which of the Boolean expressions below is
incorrect?
A. (true) && (3 => 4)
B. !(x > 0) && (x > 0)
C. (x > 0) || (x < 0)
D. (x != 0) || (x = 0)
E. (-10 < x < 0)
Your answer A is incorrect
The correct answer is ADE
Explanation: a: (3 => 4) should be (3 >= 4), d:
(x = 0) should be (x == 0), and e: should be
(-10 < x) && (x < 0)
3.22 Which of the following is the correct
expression that evaluates to true if the number
x is between 1 and 100 or the number is
negative?
A. 1 < x < 100 && x < 0
B. ((x < 100) && (x > 1)) || (x
< 0)
C. ((x < 100) && (x > 1)) && (x
< 0)
[Link] 13/24
11/21/24, 1:43 AM Introduction to Java Programming
D. (1 > x > 100) || (x < 0)
Your answer A is incorrect
The correct answer is B
Explanation: A and D have syntax errors. B
uses || for the OR operator. The correct answer
is B.
3.23 Assume x = 4 and y = 5, which of the
following is true?
A. x < 5 && y < 5
B. x < 5 || y < 5
C. x > 5 && y > 5
D. x > 5 || y > 5
Your answer A is incorrect
The correct answer is B
Explanation: x < 5 is true, but y < 5 is false. So
A is false. B is true. C and D are both false,
because x > 5 is false and y > 5 is false. The
correct answer is B.
3.24 Assume x = 4, which of the following is
true?
A. !(x == 4)
B. x != 4
C. x == 5
D. x != 5
Your answer A is incorrect
The correct answer is D
Explanation: D is true. All others are false.
[Link] 14/24
11/21/24, 1:43 AM Introduction to Java Programming
3.25 Assume x = 4 and y = 5, which of the
following is true?
A. !(x == 4) ^ y != 5
B. x != 4 ^ y == 5
C. x == 5 ^ y == 4
D. x != 5 ^ y != 4
Your answer A is incorrect
The correct answer is B
Explanation: x != 4 is false and y == 5 is true.
So B is correct.
Section 3.11 Determining Leap Year
3.26 Given |x| <= 4, which of the following is
true?
A. x <= 4 && x >= 4
B. x <= 4 && x > -4
C. x <= 4 && x >= -4
D. x <= 4 || x >= -4
Your answer A is incorrect
The correct answer is C
Explanation: |x| <= 4 means -4 <= x <= 4. That
is x <= 4 and x >= -4. |x| <= 4 is true for x
being -4, -3, 0, 2, 4, etc. So the correct answer
is C.
3.27 Given |x| >= 4, which of the following is
true?
A. x >= 4 && x <= -4
B. x >= 4 || x <= -4
C. x >= 4 && x < -4
D. x >= 4 || x < -4
[Link] 15/24
11/21/24, 1:43 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
Explanation: |x| >= 4 means x >= 4 or x <= -4.
|x| >= 4 is true for x being -4, -5, -6, 4, 5, 6, etc.
So B is correct.
3.28 Which of the following is equivalent to x !=
y?
A. ! (x == y)
B. x > y && x < y
C. x > y || x < y
D. x >= y || x <= y
Your answer A is incorrect
The correct answer is AC
Explanation: x != y means !(x == y) and x > y
|| x < y.
Section 3.12 Lottery
3.29 Suppose x=10 and y=10. What is x after
evaluating the expression (y > 10) && (x-- >
10)?
A. 9
B. 10
C. 11
Your answer A is incorrect
The correct answer is B
Explanation: For the && operator, the right
operand is not evaluated, if the left operand is
evaluated as false.
[Link] 16/24
11/21/24, 1:43 AM Introduction to Java Programming
3.30 Suppose x=10 and y=10. What is x after
evaluating the expression (y > 10) && (x++ >
10).
A. 9
B. 10
C. 11
Your answer A is incorrect
The correct answer is B
Explanation: For the && operator, the right
operand is not evaluated, if the left operand is
evaluated as false.
3.31 Suppose x=10 and y=10. What is x after
evaluating the expression (y >= 10) || (x-- >
10).
A. 9
B. 10
C. 11
Your answer A is incorrect
The correct answer is B
Explanation: For the || operator, the right
operand is not evaluated, if the left operand is
evaluated as true.
3.32 Suppose x=10 and y=10. What is x after
evaluating the expression (y >= 10) || (x++ >
10).
A. 9
B. 10
C. 11
Your answer A is incorrect
[Link] 17/24
11/21/24, 1:43 AM Introduction to Java Programming
The correct answer is B
Explanation: For the || operator, the right
operand is not evaluated, if the left operand is
evaluated as true.
3.33 Analyze the following code:
if (x < 100) && (x > 10)
[Link]("x is between 10
and 100");
A. The statement has compile
errors because (x<100) & (x >
10) must be enclosed inside
parentheses.
B. The statement has compile
errors because (x<100) & (x >
10) must be enclosed inside
parentheses and the println(?)
statement must be put inside a
block.
C. The statement compiles fine.
D. The statement compiles fine,
but has a runtime error.
Your answer is correct
Explanation: The condition for an if statement
must be enclosed in the parentheses. The
correct answer is A.
3.34 Which of the following are so called short-
circuit operators?
A. &&
B. &
C. ||
D. |
[Link] 18/24
11/21/24, 1:43 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is AC
Explanation: && and || are short-circuit
operator, meaning that if the left operand can
determine the result of the operation, the right
operand will be skipped.
Section 3.13 switch Statements
3.35 What is y after the following switch
statement is executed?
int x = 3; int y = 4;
switch (x + 3) {
case 6: y = 0;
case 7: y = 1;
default: y += 1;
}
A. 1
B. 2
C. 3
D. 4
E. 0
Your answer A is incorrect
The correct answer is B
Explanation: Since x is 3, x + 3 is 6. So, case 6
is executed. Since there is no break statement,
the statement in the next case is executed. y is
now 1. Finally y += 1 adds 1 to y. So y is 2.
The correct answer is B.
3.36 Analyze the following program fragment:
int x;
double d = 1.5;
[Link] 19/24
11/21/24, 1:43 AM Introduction to Java Programming
switch (d) {
case 1.0: x = 1;
case 1.5: x = 2;
case 2.0: x = 3;
}
A. The program has a compile
error because the required
break statement is missing in
the switch statement.
B. The program has a compile
error because the required
default case is missing in the
switch statement.
C. The switch control variable
cannot be double.
D. No errors.
Your answer A is incorrect
The correct answer is C
Explanation: The switch value cannot be a
floating-point number. So the correct answer is
C.
Section 3.14 Conditional Expressions
3.37 What is y after the following statement is
executed?
x = 0;
y = (x > 0) ? 10 : -10;
A. -10
B. 0
C. 10
D. 20
E. Illegal expression
Your answer is correct
[Link] 20/24
11/21/24, 1:43 AM Introduction to Java Programming
Explanation: This conditional operator is
correct. It assigns -10 to y since x > 0 is false.
3.38 Analyze the following code fragments that
assign a boolean value to the variable even.
Code 1:
if (number % 2 == 0)
even = true;
else
even = false;
Code 2:
even = (number % 2 == 0) ? true: false;
Code 3:
even = number % 2 == 0;
A. Code 2 has a compile error,
because you cannot have true
and false literals in the
conditional expression.
B. Code 3 has a compile error,
because you attempt to assign
number to even.
C. All three are correct, but
Code 1 is preferred.
D. All three are correct, but
Code 2 is preferred.
E. All three are correct, but
Code 3 is preferred.
Your answer A is incorrect
The correct answer is E
Explanation: Code 3 is the simplest. Code 1
and Code 2 contain redundant code.
[Link] 21/24
11/21/24, 1:43 AM Introduction to Java Programming
3.39 What is the output of the following code?
boolean even = false;
[Link]((even ? "true" : "false"));
A. true
B. false
C. nothing
D. true false
Your answer A is incorrect
The correct answer is B
Explanation: Since even is false, the
conditional expression yields false. The correct
answer is B.
Section 3.15 Operator Precedence and
Associativity
3.40 The order of the precedence (from high to
low) of the operators binary +, *, &&, ||, ^ is:
A. &&, ||, ^, *, +
B. *, +, &&, ||, ^
C. *, +, ^, &&, ||
D. *, +, ^, ||, &&
E. ^, ||, &&, *, +
Your answer A is incorrect
The correct answer is C
Explanation: See the table for the operator
precedence order. The correct answer is C.
3.41 What is y displayed in the following code?
public class Test1 {
public static void main(String[] args)
{
[Link] 22/24
11/21/24, 1:43 AM Introduction to Java Programming
int x = 1;
int y = x = x + 1;
[Link]("y is " + y);
}
}
A. y is 0.
B. y is 1 because x is assigned
to y first.
C. y is 2 because x + 1 is
assigned to x and then x is
assigned to y.
D. The program has a compile
error since x is redeclared in
the statement int y = x = x +
1.
Your answer A is incorrect
The correct answer is C
Explanation: The = operator is right-
associative.
3.42 Which of the following operators are right-
associative.
A. *
B. + (binary +)
C. %
D. &&
E. =
Your answer A is incorrect
The correct answer is E
Explanation: Assignment operators including
augmented assignment operators are right-
associative. The correct answer is E.
[Link] 23/24
11/21/24, 1:43 AM Introduction to Java Programming
3.43 What is the value of the following
expression?
true || true && false
A. true
B. false
Your answer is correct
Explanation: && has higher precedence than ||,
so && is evaluated first.
3.44 Which of the following statements are true?
A. (x > 0 && x < 10) is same as
((x > 0) && (x < 10))
B. (x > 0 || x < 10) is same as
((x > 0) || (x < 10))
C. (x > 0 || x < 10 && y < 0) is
same as (x > 0 || (x < 10 && y
< 0))
D. (x > 0 || x < 10 && y < 0) is
same as ((x > 0 || x < 10) &&
y < 0)
Your answer A is incorrect
The correct answer is ABC
Explanation: In D, && is evaluated before the
|| operator. So (x > 0 || x < 10 && y < 0) is not
same as ((x > 0 || x < 10) && y < 0).
[Link] 24/24
11/21/24, 1:49 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 4 Mathematical Functions,
Characters, and Strings
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 4.2 Common Mathematical Functions
Section 4.2.1 Trigonometric Methdos
4.1 To obtain the sine of 35 degrees, use _______.
A. [Link](35)
B. [Link]([Link](35))
C. [Link]([Link](35))
D. [Link]([Link](35))
E. [Link]([Link](35))
Your answer A is incorrect
The correct answer is B
[Link] 1/18
11/21/24, 1:49 AM Introduction to Java Programming
Explanation: Note the trig methods use the radians
for angles.
4.2 To obtain the arc sine of 0.5, use _______.
A. [Link](0.5)
B. [Link]([Link](0.5))
C. [Link]([Link](0.5))
D. [Link](0.5)
Your answer is correct
Explanation: Note the trig methods use the radians
for angles.
4.3 [Link](0.5) returns _______.
A. 30
B. [Link](30)
C. [Link] / 4
D. [Link] / 2
Your answer A is incorrect
The correct answer is B
Explanation: Note that [Link] returns an angle in
radians.
4.4 [Link]([Link]) returns _______.
A. 0.0
B. 1.0
C. 0.5
D. 0.4
Your answer is correct
Explanation: Note that [Link] is 180 degrees.
4.5 [Link]([Link]) returns _______.
A. 0.0
B. 1.0
[Link] 2/18
11/21/24, 1:49 AM Introduction to Java Programming
C. -1.0
D. 0.5
Your answer A is incorrect
The correct answer is C
Explanation: Note that [Link] is 180 degrees.
Section 4.2.3 The Rounding Methods
4.6 What is [Link](3.6)?
A. 3.0
B. 3
C. 4
D. 4.0
Your answer A is incorrect
The correct answer is C
Explanation: Note that round returns an int value
4.7 What is [Link](3.6)?
A. 3.0
B. 3
C. 4.0
D. 5.0
Your answer A is incorrect
The correct answer is C
Explanation: Note that rint returns a double value
4.8 What is [Link](3.5)?
A. 3.0
B. 3
C. 4
D. 4.0
E. 5.0
Your answer A is incorrect
[Link] 3/18
11/21/24, 1:49 AM Introduction to Java Programming
The correct answer is D
Explanation: rint returns the nearest even integer as a
double since 3.5 is equally close to 3.0 and 4.0.
4.9 What is [Link](3.6)?
A. 3.0
B. 3
C. 4.0
D. 5.0
Your answer A is incorrect
The correct answer is C
Explanation: Note that ceil returns a double value
4.10 What is [Link](3.6)?
A. 3.0
B. 3
C. 4
D. 5.0
Your answer is correct
Explanation: Note that floor returns a double value
Section 4.3 Character Data Type and
Operations Section 4.3.1 Unicode and ASCII Code
4.11 Which of the following is the correct expression
of character 4?
A. 4
B. "4"
C. '\0004'
D. '4'
Your answer A is incorrect
The correct answer is D
Explanation: You have to write '4'.
[Link] 4/18
11/21/24, 1:49 AM Introduction to Java Programming
4.12 A Java character is stored in __________.
A. one byte
B. two bytes
C. three bytes
D. four bytes
Your answer A is incorrect
The correct answer is B
Explanation: Java characters use Unicode encoding.
4.13 The Unicode of 'a' is 97. What is the Unicode for
'c'?
A. 96
B. 97
C. 98
D. 99
Your answer A is incorrect
The correct answer is D
Explanation: The Unicode for letters and numbers
are allocated in a natural order. So b is after a and c is
after b, and so on.
Section 4.3.2 Escape Sequences for Special
Characters
4.14 Which of the following statement prints
smith\exam1\[Link]?
A.
[Link]("smith\exam1\[Link]");
B.
[Link]("smith\\exam1\\[Link]")
C.
[Link]("smith\"exam1\"[Link]")
D.
[Link]("smith"\exam1"\[Link]")
Your answer A is incorrect
[Link] 5/18
11/21/24, 1:49 AM Introduction to Java Programming
The correct answer is B
Explanation: To represent the character, use \,
because it is an escape character.
Section 4.3.3 Casting between char and Numeric
Types
4.15 Suppose x is a char variable with a value 'b'. What
is the output of the statement
[Link](++x)?
A. a
B. b
C. c
D. d
Your answer A is incorrect
The correct answer is C
Explanation: The ++ and -- operators can be applied
to a char variable. ++x is preincrement. x is 'b' before
++x. After ++x, x becomes c.
4.16 Suppose i is an int type variable. Which of the
following statements display the character whose
Unicode is stored in variable i?
A. [Link](i);
B. [Link]((char)i);
C. [Link]((int)i);
D. [Link](i + " ");
Your answer A is incorrect
The correct answer is B
Explanation: (char)i casts a number into a character.
4.17 Will [Link]((char)4) display 4?
A. Yes
B. No
Your answer A is incorrect
[Link] 6/18
11/21/24, 1:49 AM Introduction to Java Programming
The correct answer is B
Explanation: The character whose Unicode is is to
be displayed, not number 4.
4.18 What is the output of [Link]('z' - 'a')?
A. 25
B. 26
C. a
D. z
Your answer is correct
Explanation: The Unicode offset between z and a is
25.
4.19 An int variable can hold __________.
A. 'x'
B. 120
C. 120.0
D. "x"
E. "120"
Your answer A is incorrect
The correct answer is AB
Explanation: Choice A is also correct, because a
character can be implicitly cast into an int variable.
The Unicode value of character is assignment to the
int variable. In this case, the code is 120 (see
Appendix B).
4.20 Which of the following assignment statements is
correct?
A. char c = 'd';
B. char c = 100;
C. char c = "d";
D. char c = "100";
Your answer A is incorrect
[Link] 7/18
11/21/24, 1:49 AM Introduction to Java Programming
The correct answer is AB
Explanation: Choice B is also correct, because an int
value can be implicitly cast into a char variable. The
Unicode of the character is the int value. In this case,
the character is d (see Appendix B).
4.21 '3' - '2' + 'm' / 'n' is ______.
A. 0
B. 1
C. 2
D. 3
Your answer A is incorrect
The correct answer is B
Explanation: When an operand is a character in an
arithmetic expression, the character is casted to an int
value.
Section 4.3.4 Comparing and Testing Characters
4.22 To check whether a char variable ch is an
uppercase letter, you write ___________.
A. (ch >= 'A' && ch >= 'Z')
B. (ch >= 'A' && ch <= 'Z')
C. (ch >= 'A' || ch <= 'Z')
D. ('A' <= ch <= 'Z')
Your answer A is incorrect
The correct answer is B
Explanation: A is wrong because ch >= 'Z'. C is
wrong because of using ||. D is wrong because of
incorrect syntax. The correct answer is B.
4.23 Which of the following is not a correct method in
the Character class?
A. isLetterOrDigit(char)
B. isLetter(char)
C. isDigit()
[Link] 8/18
11/21/24, 1:49 AM Introduction to Java Programming
D. toLowerCase(char)
E. toUpperCase()
Your answer A is incorrect
The correct answer is CE
Explanation: isDigit() should be isDigit(char) and
toUpperCase() should be toUpperCase(char)
4.24 Suppose Character x = new Character('a'),
__________________ returns true.
A. [Link](new Character('a'))
B. [Link]('A')
C. [Link]('A')
D. [Link]('a')
E. [Link]("a")
Your answer A is incorrect
The correct answer is AD
Explanation: (B) and (C) are wrong because no
methods compareToIgnoreCase and
equalsIgnoreCase are in the Character class. (E) is
wrong because a character is not a string.
Section 4.4 The String Type Section 4.4.2 Gettiing
Characters from a String
4.25 Suppose s is a string with the value "java". What
will be assigned to x if you execute the following
code?
char x = [Link](4);
A. 'a'
B. 'v'
C. Nothing will be assigned to x,
because the execution causes the
runtime error
StringIndexOutofBoundsException.
Your answer A is incorrect
[Link] 9/18
11/21/24, 1:49 AM Introduction to Java Programming
The correct answer is C
Explanation: The string index starts from 0 and the
last index is [Link]() - 1. [Link](4) is out of
bounds.
Section 4.4.3 Concatenating Strings
4.26 The expression "Java " + 1 + 2 + 3 evaluates to
________.
A. Java123
B. Java6
C. Java 123
D. java 123
E. Illegal expression
Your answer A is incorrect
The correct answer is C
Explanation: The + operator is evaluated from left to
right. When a string adds with a number, the number
is converted into a string. The correct answer is C.
4.27 Note that the Unicode for character A is 65. The
expression "A" + 1 evaluates to ________.
A. 66
B. B
C. A1
D. Illegal expression
Your answer A is incorrect
The correct answer is C
Explanation: When a string adds with a number, the
number is converted into a string. The correct answer
is C.
4.28 Note that the Unicode for character A is 65. The
expression 'A' + 1 evaluates to ________.
A. 66
B. B
[Link] 10/18
11/21/24, 1:49 AM Introduction to Java Programming
C. A1
D. Illegal expression
Your answer is correct
Explanation: When a character adds with a number,
the character is converted into a int. The correct
answer is A.
Section 4.4.4 Converting Strings
4.29 Which of the following is the correct statement to
return JAVA?
A. toUpperCase("Java")
B. "Java".toUpperCase("Java")
C. "Java".toUpperCase()
D. [Link]("Java")
Your answer A is incorrect
The correct answer is C
Explanation: The correct method is toUpperCase().
So C is correct.
Section 4.4.7 Comparing Strings
4.30 Suppose s1 and s2 are two strings. Which of the
following statements or expressions is incorrect?
A. String s3 = s1 - s2;
B. boolean b = [Link](s2);
C. char c = s1[0];
D. char c = [Link]([Link]());
Your answer A is incorrect
The correct answer is ABCD
Explanation: A is wrong because the - operator
cannot be used for strings. B is wrong because the
compareTo method returns an int, not a boolean. C is
wrong because the [] cannot be used for accessing
string elements. D is wrong because of index out of
bounds.
[Link] 11/18
11/21/24, 1:49 AM Introduction to Java Programming
4.31 Suppose s1 and s2 are two strings. What is the
result of the following code?
[Link](s2) == [Link](s1)
A. true
B. false
Your answer is correct
Explanation: [Link](s2) and [Link](s1) are the
same.
4.32 "abc".compareTo("aba") returns ___________.
A. 1
B. 2
C. -1
D. -2
E. 0
Your answer A is incorrect
The correct answer is B
Explanation: The first two characters in the two
strings are the same. The different between the last
two characters is 2. The correct answer is B.
4.33 "AbA".compareToIgnoreCase("abC") returns
___________.
A. 1
B. 2
C. -1
D. -2
E. 0
Your answer A is incorrect
The correct answer is D
Explanation: Ignoring case, you compare aba with
abc. The first two characters in the two strings are the
[Link] 12/18
11/21/24, 1:49 AM Introduction to Java Programming
same. The different between the last two characters is
-2. The correct answer is D.
4.34 ____________________ returns true.
A.
"peter".compareToIgnoreCase("Peter")
B.
"peter".compareToIgnoreCase("peter")
C. "peter".equalsIgnoreCase("Peter")
D. "peter".equalsIgnoreCase("peter")
E. "peter".equals("peter")
Your answer A is incorrect
The correct answer is CDE
Explanation: The compareToIgnoreCase return an
int. So, A and B are wrong. Ignoring case, C, D, and
E all return true.
Section 4.4.8 Obtaining Substrings
4.35 What is the return value of
"SELECT".substring(0, 5)?
A. "SELECT"
B. "SELEC"
C. "SELE"
D. "ELECT"
Your answer A is incorrect
The correct answer is B
Explanation: Note that the substring is from index 0
to 4, which is 5 - 1. The correct answer is B.
4.36 What is the return value of
"SELECT".substring(4, 4)?
A. an empty string
B. C
C. T
D. E
[Link] 13/18
11/21/24, 1:49 AM Introduction to Java Programming
Your answer is correct
Explanation: If beginIndex is endIndex,
substring(beginIndex, endIndex) returns an empty
string with length 0. It would be a runtime error, if
beginIndex > endIndex.
Section 4.4.9 Finding a Character or a Substring in a
String
4.37 To check if a string s contains the prefix "Java",
you may write
A. if ([Link]("Java")) ...
B. if ([Link]("Java") == 0) ...
C. if ([Link](0,
4).equals("Java")) ...
D. if ([Link](0) == 'J' &&
[Link](1) == 'a' && [Link](2)
== 'v' && [Link](3) == 'a') ...
Your answer A is incorrect
The correct answer is ABCD
Explanation: They are all correct.
4.38 To check if a string s contains the suffix "Java",
you may write
A. if ([Link]("Java")) ...
B. if ([Link]("Java") >= 0)
...
C. if ([Link]([Link]() -
4).equals("Java")) ...
D. if ([Link]([Link]() -
5).equals("Java")) ...
E. if ([Link]([Link]() - 4) ==
'J' && [Link]([Link]() - 3) ==
'a' && [Link]([Link]() - 2) ==
'v' && [Link]([Link]() - 1) ==
'a') ...
[Link] 14/18
11/21/24, 1:49 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is ACE
Explanation: [Link]('Java') >= 0 does not
indicate that Java is the suffix of the string.
Section 4.4.10 Conversions between Strings and
Numbers
4.39 The __________ method parses a string s to an
int value.
A. [Link](s);
B. [Link](s);
C. [Link](s);
D. [Link](s);
Your answer A is incorrect
The correct answer is B
Explanation: The parseInt method is defined in the
Integer class. B is correct.
4.40 The __________ method parses a string s to a
double value.
A. [Link](s);
B. [Link](s);
C. [Link](s);
D. [Link](s);
Your answer A is incorrect
The correct answer is D
Explanation: The parseDouble method is defined in
the Double class. D is correct.
Section 4.6 Formatting Console Output
4.41 Which of the following are valid specifiers for the
printf statement?
A. %4c
[Link] 15/18
11/21/24, 1:49 AM Introduction to Java Programming
B. %10b
C. %6d
D. %8.2d
E. %10.2e
Your answer A is incorrect
The correct answer is ABCE
Explanation: All correct except D. D is wrong
because the specifier d is for decimal integer.
4.42 The statement [Link]("%3.1f",
1234.56) outputs ___________.
A. 123.4
B. 123.5
C. 1234.5
D. 1234.56
E. 1234.6
Your answer A is incorrect
The correct answer is E
Explanation: .1 specifies one digit after the decimal
point. The rest is rounded up. So 1234.56 is
displayed 1234.6.
4.43 The statement [Link]("%3.1e",
1234.56) outputs ___________.
A. 0.1e+04
B. 0.123456e+04
C. 0.123e+04
D. 1.2e+03
E. 1.23+03
Your answer A is incorrect
The correct answer is D
Explanation: %3.1e specifies a scientific notation
with one digit after the decimal point. So, the correct
answer is D.
[Link] 16/18
11/21/24, 1:49 AM Introduction to Java Programming
4.44 The statement [Link]("%5d", 123456)
outputs ___________.
A. 12345
B. 23456
C. 123456
D. 12345.6
Your answer A is incorrect
The correct answer is C
Explanation: %5d specifies an integer with width 5.
The width is automatically expanded if the number is
larger than the specified width. So, the correct
answer is C.
4.45 The statement [Link]("%10s", 123456)
outputs ___________. (Note: * represents a space)
A. 123456****
B. 23456*****
C. 12345*****
D. ****123456
Your answer A is incorrect
The correct answer is D
Explanation: %10s specifies to display a string with
width 10. By default, it is right justified. So, the
correct answer is D.
4.46 Analyze the following code:
int i = 3434; double d = 3434;
[Link]("%5.1f %5.1f", i, d);
A. The code compiles and runs fine to
display 3434.0 3434.0.
B. The code compiles and runs fine to
display 3434 3434.0.
C. i is an integer, but the format
specifier %5.1f specifies a format
[Link] 17/18
11/21/24, 1:49 AM Introduction to Java Programming
for double value. The code has an
error.
Your answer A is incorrect
The correct answer is C
Explanation: i is an integer, but the format specifier
%5.1f specifies a format for double value. Type does
not match. So, the correct answer is C.
[Link] 18/18
11/21/24, 1:52 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 5 Loops
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 5.2 The while Loop
5.1 How many times will the following code print
"Welcome to Java"?
int count = 0;
while (count < 10) {
[Link]("Welcome to Java");
count++;
}
A. 8
B. 9
C. 10
D. 11
E. 0
[Link] 1/24
11/21/24, 1:52 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
Explanation: The count is initialized to 0 before the
loop. The loop is executed 10 times for count from 1
to 9. When count is 10, the loop continuation
condition becomes false. The loop is finished. So, the
correct answer is C.
5.2 Analyze the following code.
int count = 0;
while (count < 100) {
// Point A
[Link]("Welcome to Java!");
count++;
// Point B
}
// Point C
A. count < 100 is always true at
Point A
B. count < 100 is always true at
Point B
C. count < 100 is always false at
Point B
D. count < 100 is always true at
Point C
E. count < 100 is always false at
Point C
Your answer A is incorrect
The correct answer is AE
Explanation: The count is initialized to 0 before the
loop. The loop is executed 100 times for count from
0 to 99. Inside the loop body, at Point A, count < 100
is true. After executing count++, count < 100 in Point
B may become false. After the loop is exited, count <
100 is false at Point C. So, the correct answer is AE.
[Link] 2/24
11/21/24, 1:52 AM Introduction to Java Programming
Section 5.3 Case Study: Guessing Numbers
5.3 How many times will the following code print
"Welcome to Java"?
int count = 0;
while (count++ < 10) {
[Link]("Welcome to Java");
}
A. 8
B. 9
C. 10
D. 11
E. 0
Your answer A is incorrect
The correct answer is C
Explanation: The count is initialized to 0 before the
loop. (count++ < 10) increments count by 1 and uses
the old count value to check if count < 10. So, the
loop is executed 10 times for count from 0 to 9. The
correct answer is C.
5.4 What is the output of the following code?
int x = 0;
while (x < 4) {
x = x + 1;
}
[Link]("x is " + x);
A. x is 0
B. x is 1
C. x is 2
D. x is 3
E. x is 4
Your answer A is incorrect
The correct answer is E
Explanation: x is 0 before the loop. The loop is
executed 4 times for x from 0 to 3. When x is 4 the
loop exits. So, the correct answer is E.
[Link] 3/24
11/21/24, 1:52 AM Introduction to Java Programming
Section 5.5 Controlling a Loop with User
Confirmation or a Sentinel Value
5.5 What will be displayed when the following code is
executed?
int number = 6;
while (number > 0) {
number -= 3;
[Link](number + " ");
}
A. 6 3 0
B. 6 3
C. 3 0
D. 3 0 -3
E. 0 -3
Your answer A is incorrect
The correct answer is C
Explanation: number is 6 before the loop. In the first
iteration, number is reduced to 3. In the second
iteration, number is reduced to 0. The loop is now
finished. The loop body is executed 2 times for
number 6 and 3. Since number is reduced by 3 before
the print statement. 3 and 0 and displayed. So, the
correct answer is C.
Section 5.6 The do-while Loop
5.6 How many times will the following code print
"Welcome to Java"?
int count = 0;
do {
[Link]("Welcome to Java");
count++;
} while (count < 10);
A. 8
B. 9
C. 10
D. 11
[Link] 4/24
11/21/24, 1:52 AM Introduction to Java Programming
E. 0
Your answer A is incorrect
The correct answer is C
Explanation: The count is initialized to 0 before the
loop. The loop is executed 10 times for count from 0
to 9. When count is 10, the loop continuation
condition becomes false. The loop is finished. So, the
correct answer is C.
5.7 How many times will the following code print
"Welcome to Java"?
int count = 0;
do {
[Link]("Welcome to Java");
} while (count++ < 10);
A. 8
B. 9
C. 10
D. 11
E. 0
Your answer A is incorrect
The correct answer is D
Explanation: The count is initialized to 0 before the
loop. The loop is executed for the first time when
count is 0. (count++ < 10) increments count by 1 and
uses the old count value to check if count < 10. So,
the loop is executed 11 times for count from 0 to 10.
Note that when count is 10, the loop body is executed
before the loop is exited. The correct answer is D.
5.8 How many times will the following code print
"Welcome to Java"?
int count = 0;
do {
[Link]("Welcome to Java");
} while (++count < 10);
[Link] 5/24
11/21/24, 1:52 AM Introduction to Java Programming
A. 8
B. 9
C. 10
D. 11
E. 0
Your answer A is incorrect
The correct answer is C
Explanation: The count is initialized to 0 before the
loop. The loop is executed for the first time when
count is 0. (++count < 10) increments count by 1 and
uses the new count value to check if count < 10. So,
the loop is executed 10 times for count from 0 to 9.
Note that when count is 9, ++count becomes 10, the
loop exits. The correct answer is C.
5.9 What is the value in count after the following loop
is executed?
int count = 0;
do {
[Link]("Welcome to Java");
} while (count++ < 9);
[Link](count);
A. 8
B. 9
C. 10
D. 11
E. 0
Your answer A is incorrect
The correct answer is C
Explanation: The count is initialized to 0 before the
loop. The loop is executed for the first time when
count is 0. (count++ < 9) increments count by 1 and
uses the old count value to check if count < 9. So, the
loop is executed 10 times for count from 0 to 9. Note
that when count is 9, the loop body is executed and
then count++ increments count to 10. The previous
count value 9 < 9 is false. So the loop is finished.
[Link] 6/24
11/21/24, 1:52 AM Introduction to Java Programming
Now count becomes 10 after the loop exits. The
correct answer is C.
Section 5.7 The for Loop
5.10 Analyze the following statement:
double sum = 0;
for (double d = 0; d < 10;) {
d += 0.1;
sum += sum + d;
}
A. The program has a compile error
because the adjustment is missing
in the for loop.
B. The program has a compile error
because the control variable in the
for loop cannot be of the double
type.
C. The program runs in an infinite
loop because d < 10 would always be
true.
D. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is D
Explanation: In this loop, the loop initial action is d =
0, the continuation condition is d < 10, and the
action-after-each-iteration is blank. Note that any of
these three parts in the loop can be omitted. So, the
loop is correct. The correction answer is (D).
5.11 Which of the following loops prints "Welcome to
Java" 10 times?
A:
for (int count = 1; count <= 10; count++) {
[Link]("Welcome to Java");
}
B:
[Link] 7/24
11/21/24, 1:52 AM Introduction to Java Programming
for (int count = 0; count < 10; count++) {
[Link]("Welcome to Java");
}
C:
for (int count = 1; count < 10; count++) {
[Link]("Welcome to Java");
}
D:
for (int count = 0; count <= 10; count++) {
[Link]("Welcome to Java");
}
A. BD
B. ABC
C. AC
D. BC
E. AB
Your answer A is incorrect
The correct answer is E
Explanation: In (A), the loop displays Welcome to
Java 10 times for count from 1 to 10. In (B), the loop
displays Welcome to Java 10 times for count from 0
to 9. In (C), the loop displays Welcome to Java 9
times for count from 1 to 9. In (D), the loop displays
Welcome to Java 11 times for count from 0 to 10.
Therefore, the correct answer is AB.
5.12 Which of the following loops correctly computes
1/2 + 2/3 + 3/4 + ... + 99/100?
A:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum = i / (i + 1);
}
[Link]("Sum is " + sum);
B:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1);
}
[Link] 8/24
11/21/24, 1:52 AM Introduction to Java Programming
[Link]("Sum is " + sum);
C:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += 1.0 * i / (i + 1);
}
[Link]("Sum is " + sum);
D:
double sum = 0;
for (int i = 1; i <= 99; i++) {
sum += i / (i + 1.0);
}
[Link]("Sum is " + sum);
E:
double sum = 0;
for (int i = 1; i < 99; i++) {
sum += i / (i + 1.0);
}
[Link]("Sum is " + sum);
A. BCD
B. ABCD
C. B
D. CDE
E. CD
Your answer A is incorrect
The correct answer is E
Explanation: Note that 1 / 2 is 0.5 in a math
expression. In Java, however, integer division yields
an integer. The fraction part is truncated. Therefore, i
/ (i + 1) is 0. (A) and (B) are incorrect. (E) is
incorrect because the last i in the loop is 98. So the
last item 99 / 100.0 is not added to sum. So, the
correct answer is CD.
5.13 The following loop displays _______________.
for (int i = 1; i <= 10; i++) {
[Link](i + " ");
i++;
}
[Link] 9/24
11/21/24, 1:52 AM Introduction to Java Programming
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5
D. 1 3 5 7 9
E. 2 4 6 8 10
Your answer A is incorrect
The correct answer is D
Explanation: In this for loop, i is initialized to 1. i++
adds 1 to i at the end of the iteration. In the action-
after-each-iteration, i is again incremented by 1. So, i
is in effect incremented twice. So, i is 1, then 3, 5, 7,
and 9. The correct answer is D.
5.14 Do the following two statements in (I) and (II)
result in the same value in sum?
(I):
for (int i = 0; i < 10; ++i) {
sum += i;
}
(II):
for (int i = 0; i < 10; i++) {
sum += i;
}
A. Yes
B. No
Your answer is correct
Explanation: In this case, ++i and i++ are used
standalone with no side-effect. So, (I) and (II) are
equivalent. The correct answer is A.
5.15 What is the output for y?
int y = 0;
for (int i = 0; i < 10; ++i) {
y += i;
}
[Link](y);
[Link] 10/24
11/21/24, 1:52 AM Introduction to Java Programming
A. 10
B. 11
C. 12
D. 13
E. 45
Your answer A is incorrect
The correct answer is E
Explanation: The loop is executed 10 times for i from
0 to 9. Each time, i is added to y. So y = 0 + 1 + 2 + 3
+ 4 + 5 + 6 + 7 + 8 + 9, which 45. The correct answer
is E.
5.16 What is i after the following for loop?
int y = 0;
for (int i = 0; i < 10; ++i) {
y += i;
}
A. 9
B. 10
C. 11
D. undefined
Your answer A is incorrect
The correct answer is D
Explanation: The scope for i is inside the loop. After
the loop, i is not defined. So, the correct answer is D.
5.17 Is the following loop correct?
for ( ; ; );
A. Yes
B. No
Your answer is correct
Explanation: Yes. This is equivalent to for (; true; ).
[Link] 11/24
11/21/24, 1:52 AM Introduction to Java Programming
Section 5.8 Which Loop to Use?
5.18 Analyze the following fragment:
double sum = 0;
double d = 0;
while (d != 10.0) {
d += 0.1;
sum += sum + d;
}
A. The program does not compile
because sum and d are declared
double, but assigned with integer
value 0.
B. The program never stops because d
is always 0.1 inside the loop.
C. The program may not stop because
of the phenomenon referred to as
numerical inaccuracy for operating
with floating-point numbers.
D. After the loop, sum is 0 + 0.1 +
0.2 + 0.3 + ... + 1.9
Your answer A is incorrect
The correct answer is C
Explanation: The correct answer is C. There is no
guarantee that d will be exactly 10.0 because real
numbers are represented using approximation in a
computer system.
5.19 Analyze the following code:
public class Test {
public static void main (String[] args) {
int i = 0;
for (i = 0; i < 10; i++);
[Link](i + 4);
}
}
A. The program has a compile error
because of the semicolon (;) on the
for loop line.
[Link] 12/24
11/21/24, 1:52 AM Introduction to Java Programming
B. The program compiles despite the
semicolon (;) on the for loop line,
and displays 4.
C. The program compiles despite the
semicolon (;) on the for loop line,
and displays 14.
D. The for loop in this program is
same as for (i = 0; i < 10; i++) {
}; [Link](i + 4);
Your answer A is incorrect
The correct answer is CD
Explanation: This is a logic error.
[Link](i + 4) is not a part the for loop
because the for loop ends with the last semicolon at
for (i=0; i < 10; i++);
Section 5.9 Nested Loops
5.20 How many times is the println statement
executed?
for (int i = 0; i < 10; i++)
for (int j = 0; j < i; j++)
[Link](i * j)
A. 100
B. 20
C. 10
D. 45
Your answer A is incorrect
The correct answer is D
5.21 Which pattern is produced by the following code?
for (int i = 1; i <= 6; i++) {
for (int j = 6; j >= 1; j--)
[Link](j <= i ? j + " " : " " +
" ");
[Link]();
}
[Link] 13/24
11/21/24, 1:52 AM Introduction to Java Programming
Pattern A Pattern B Pattern C Patte
1 1 2 3 4 5 6 1 1 2 3
1 2 1 2 3 4 5 2 1 1 2
1 2 3 1 2 3 4 3 2 1 1
1 2 3 4 1 2 3 4 3 2 1
1 2 3 4 5 1 2 5 4 3 2 1
1 2 3 4 5 6 1 6 5 4 3 2 1
A. Pattern A
B. Pattern B
C. Pattern C
D. Pattern D
Your answer A is incorrect
The correct answer is C
Explanation: The outer loop displays a line. The
inner loop displays all the numbers in the line. The
outer loop is repeated 6 times for i from 1 to 6. For
each i, the inner loops displays i as the first number
in the line since j is from 6 to 1. j is printed for j <= i.
Otherwise, a space is printed. Clearly, this code will
print Pattern C.
5.22 How many times is the println statement
executed?
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
[Link](i * j);
A. 100
B. 20
C. 10
D. 45
Your answer is correct
Explanation: The outer loop is executed 10 times for
i from 0 to 9 and the inner loop is executed 10 times
from j from 0 to 9. So the print statement is executed
100 times. The correct answer is A.
[Link] 14/24
11/21/24, 1:52 AM Introduction to Java Programming
Section 5.10 Minimizing Numerical Errors
5.23 To add 0.01 + 0.02 + ... + 1.00, what order should
you use to add the numbers to get better accuracy?
A. add 0.01, 0.02, ..., 1.00 in this
order to a sum variable whose
initial value is 0.
B. add 1.00, 0.99, 0.98, ..., 0.02,
0.01 in this order to a sum
variable whose initial value is 0.
Your answer is correct
Explanation: Adding the numbers in the order
specified in A will result in a more accurate result
than in B, because two numbers to be added will be
about the same size.
5.24 Analyze the following code.
double sum = 0;
for (double d = 0; d < 10; sum += sum + d) {
d += 0.1;
}
A. The program has a syntax error
because the adjustment statement is
incorrect in the for loop.
B. The program has a syntax error
because the control variable in the
for loop cannot be of the double
type.
C. The program compiles but does not
stop because d would always be less
than 10.
D. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is D
Explanation: In this loop, the loop initial action is d =
0, the continuation condition is d < 10, and the
[Link] 15/24
11/21/24, 1:52 AM Introduction to Java Programming
action-after-each-iteration is sum += sum + d. The
loop body is d += 1. This code is correct in syntax. d
is initially 0 and d += 0.1 adds 0.1 to d in each
iteration. Eventually d will be greater than or equal to
10. So the loop will terminate. The correct answer for
this question is (D) The program compiles and runs
fine.
Section 5.11 Case Studies
5.25 What is y after the following for loop statement is
executed?
int y = 0;
for (int i = 0; i < 10; ++i) {
y += 1;
}
A. 9
B. 10
C. 11
D. 12
Your answer A is incorrect
The correct answer is B
Explanation: Before the loop, y is 0. The loop is
executed 10 times. Each time, 1 is added to y. So,
after the loop is finished, y is 10. The correct answer
is (B).
Section 5.12 Keywords break and continue
5.26 Will the following program terminate?
int balance = 10;
while (true) {
if (balance < 9)
break;
balance = balance - 9;
}
A. Yes
B. No
[Link] 16/24
11/21/24, 1:52 AM Introduction to Java Programming
Your answer is correct
Explanation: Yes. Before the loop, balance is 10. The
loop-continuation-condition is always true. In the
first iteration, balance is reduced to 1. In the second
iteration, the break statement is executed since
(balance < 9) is now true. The correct answer for this
question is A.
5.27 What is sum after the following loop terminates?
int sum = 0;
int item = 0;
do {
item++;
sum += item;
if (sum > 4)
break;
}
while (item < 5);
A. 5
B. 6
C. 7
D. 8
E. 9
Your answer A is incorrect
The correct answer is B
Explanation: sum and item are initialized to 0 before
the loop. In the loop, item++ increments item by 1
and item is then added to sum. If sum > 4, the break
statement exits the loop. item is initially 0, then 1, 2,
3 and sum is initially 0, and then 1, 3, and 6. When
sum is 6, (sum > 4) is true, which causes the break
statement to be executed. So, the correct answer is B.
5.28 What is the output after the following loop
terminates?
int number = 25;
int i;
[Link] 17/24
11/21/24, 1:52 AM Introduction to Java Programming
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
[Link]("i is " + i + " isPrime is " + isPrim
A. i is 5 isPrime is true
B. i is 5 isPrime is false
C. i is 6 isPrime is true
D. i is 6 isPrime is false
Your answer A is incorrect
The correct answer is D
Explanation: The code tests if number is prime by
dividing the number with possible divisors 2, 3, 4,
and so on. Initially, isPrime is set to true. Once a
divisor is found (i.e., number % i == 0 is true),
isPrime is set to false. The loop continuation
condition now becomes false. The loop ends. If no
divisor is found after the loop is finished, isPrime
remains true. Since number is 25, number % i == 0 is
true when i is 5. In this case, isPrime is set to false
and i++ increments i by 1 in the action-after-each-
iteration. So, the output is that i is 6 and isPrime is
false. The correct anwer is D.
5.29 What is the output after the following loop
terminates?
int number = 25;
int i;
boolean isPrime = true;
for (i = 2; i < number; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
[Link] 18/24
11/21/24, 1:52 AM Introduction to Java Programming
[Link]("i is " + i + " isPrime is " + isPrim
A. i is 5 isPrime is true
B. i is 5 isPrime is false
C. i is 6 isPrime is true
D. i is 6 isPrime is false
Your answer A is incorrect
The correct answer is B
Explanation: The code tests if number is prime by
dividing the number with possible divisors 2, 3, 4,
and so on. Initially, isPrime is set to true. Once a
divisor is found (i.e., number % i == 0 is true),
isPrime is set to false and the break statement is then
executed to exit the loop. If no divisor is found after
the loop is finished, isPrime remains true. Since
number is 25, number % i == 0 is true when i is 5. In
this case, isPrime is set to false and the loop exits.
So, the output is that i is 5 and isPrime is true. The
correct answer is B.
5.30 What is sum after the following loop terminates?
int sum = 0;
int item = 0;
do {
item++;
if (sum >= 4)
continue;
sum += item;
}
while (item < 5);
A. 6
B. 7
C. 8
D. 9
E. 10
Your answer is correct
Explanation: In this loop, when sum >= 4, the
continue statement is executed to exit the current
[Link] 19/24
11/21/24, 1:52 AM Introduction to Java Programming
iteration so the next statement sum += item after the
if statement will not be executed. The loop keeps
adding item to sum for item 1, 2, 3, and so on. So
sum is 1, 2, and 6. When sum is 6, sum >=4 is true,
the continue statement is executed to skip the rest of
the iteration. When the loop ends, sum is still 6. So,
the correct answer is A.
5.31 Will the following program terminate?
int balance = 10;
while (true) {
if (balance < 9)
continue;
balance = balance - 9;
}
A. Yes
B. No
Your answer A is incorrect
The correct answer is B
Explanation: Before the loop, balance is 10. In the
loop, balance becomes 1. The loop-continuation-
condition is always true. When balance < 9 is true,
the continue statement is executed to skip the rest
statement in the iteration. So the loop continues in an
infinite loop. So, the correct answer is B.
5.32 What balance after the following code is
executed?
int balance = 10;
while (balance >= 1) {
if (balance < 9)
continue;
balance = balance - 9;
}
A. -1
B. 0
[Link] 20/24
11/21/24, 1:52 AM Introduction to Java Programming
C. 1
D. 2
E. The loop does not end
Your answer A is incorrect
The correct answer is E
Explanation: Before the loop, balance is 10. The
loop-continuation-condition is true (10 >= 1). In the
first iteration, balance is reduced to 1. Since 1 >= 1 is
true, the loop body is executed. Since balance < 9 is
true, the continue statement is executed to skip the
rest statement in the iteration. balance continues to be
1 and the continue statement is executed to skip the
rest statement in the iteration. So the loop runs
infinitely. So the correct answer to this question is E.
5.33 What is the value of balance after the following
code is executed?
int balance = 10;
while (balance >= 1) {
if (balance < 9)
break;
balance = balance - 9;
}
A. -1
B. 0
C. 1
D. 2
Your answer A is incorrect
The correct answer is C
Explanation: Before the loop, balance is 10. The
loop-continuation-condition is true (10 >= 1). In the
first iteration, balance is reduced to 1. Since 1 >= 1 is
true, the loop body is executed. Since balance < 9 is
true, the break statement is executed to exit the loop.
So, balance is 1 after the loop is finished. The correct
answer for this question is C.
[Link] 21/24
11/21/24, 1:52 AM Introduction to Java Programming
Section 5.13 Case Study: Checking Palindromes
5.34 What is the number of iterations in the following
loop?
for (int i = 1; i < n; i++) {
// iteration
}
A. 2*n
B. n
C. n - 1
D. n + 1
Your answer A is incorrect
The correct answer is C
Explanation: The loop is executed n ? 1 times for i
from 1 to n ? 1. So, the correct answer is C.
5.35 What is the number of iterations in the following
loop?
for (int i = 1; i <= n; i++) {
// iteration
}
A. 2*n
B. n
C. n - 1
D. n + 1
Your answer A is incorrect
The correct answer is B
Explanation: The loop is executed n times for i from
1 to n. So, the correct answer is B.
Section 5.14 Case Study: Displaying Prime Numbers
5.36 Suppose the input for number is 9. What is the
output from running the following program?
import [Link];
[Link] 22/24
11/21/24, 1:52 AM Introduction to Java Programming
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
int i;
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
[Link]("i is " + i);
if (isPrime)
[Link](number + " is
prime");
else
[Link](number + " is not
prime");
}
}
A. i is 3 followed by 9 is prime
B. i is 3 followed by 9 is not prime
C. i is 4 followed by 9 is prime
D. i is 4 followed by 9 is not prime
Your answer A is incorrect
The correct answer is D
Explanation: The input number is 9. isPrime is
initialized to true. The loop tests if number is
divisible by i for i from 2, 3, and so on. When i is 3,
isPrime is false. The loop continuation condition
becomes false. The loop is not finished. Before the
loop continuation condition is checked, i++
increments i by 1. So, output is that i is 4 and
following by 9 is not prime. So, the correct answer is
is executed n times for i from 1 to n. So, the correct
answer is D.
[Link] 23/24
11/21/24, 1:52 AM Introduction to Java Programming
5.37 Analyze the following code:
import [Link];
public class Test {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 100000; i++) {
Scanner input = new Scanner([Link]);
sum += [Link]();
}
}
}
A. The program does not compile
because the Scanner input = new
Scanner([Link]); statement is
inside the loop.
B. The program compiles, but does not
run because the Scanner input = new
Scanner([Link]); statement is
inside the loop.
C. The program compiles and runs, but
it is not efficient and unnecessary
to execute the Scanner input = new
Scanner([Link]); statement
inside the loop. You should move
the statement before the loop.
D. The program compiles, but does not
run because there is not prompting
message for entering the input.
Your answer A is incorrect
The correct answer is C
Explanation: To receive input from the keyboard, you
need to create an input object from the Scanner class.
You should create this object only once in the
program. Placing the statement Scanner input = new
Scanner([Link]) in the loop causes it to be created
multiple times, which is a bad practice and could
lead to potential errors. So, the correct answer is C.
[Link] 24/24
11/21/24, 1:55 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of
additional quiz is available for instructors using Quiz
Generator from the Instructor's Resource Website. Videos for
Java, Python, and C++ can be found at
[Link]
Chapter 6 Methods
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book
and edition you are using. Thanks!
Sections 6.2 Defining a Method
6.1 Suppose your method does not return any
value, which of the following keywords can be
used as a return type?
A. void
B. int
C. double
D. public
E. None of the above
[Link] 1/16
11/21/24, 1:55 AM Introduction to Java Programming
Your answer is correct
6.2 The signature of a method consists of
____________.
A. method name
B. method name and parameter
list
C. return type, method name, and
parameter list
D. parameter list
Your answer A is incorrect
The correct answer is B
Explanation: By definition, a method signature
consists of method name and parameter list.
6.3 All Java applications must have a method
__________.
A. public static Main(String[]
args)
B. public static Main(String
args[])
C. public static void
main(String[] args)
D. public void main(String[]
args)
E. public static main(String[]
args)
Your answer A is incorrect
The correct answer is C
Explanation: Java application's starting method
is the main method.
[Link] 2/16
11/21/24, 1:55 AM Introduction to Java Programming
Sections 6.3 Calling a Method
6.4 Arguments to methods always appear within
__________.
A. brackets
B. parentheses
C. curly braces
D. quotation marks
Your answer A is incorrect
The correct answer is B
6.5 Does the return statement in the following
method cause compile errors?
public static void main(String[] args) {
int max = 0;
if (max != 0)
[Link](max);
else
return;
}
A. Yes
B. No
Your answer A is incorrect
The correct answer is B
Explanation: It is rare, but sometimes useful to
have a return statement for circumventing the
normal flow of control in a void method.
6.6 Does the method call in the following method
cause compile errors?
public static void main(String[] args) {
[Link] 3/16
11/21/24, 1:55 AM Introduction to Java Programming
[Link](2, 4);
}
A. Yes
B. No
Your answer A is incorrect
The correct answer is B
Explanation: A value-returning method can
also be invoked as a statement in Java. In this
case, the caller simply ignores the return value.
This is rare, but permissible if the caller is not
interested in the return value.
6.7 Each time a method is invoked, the system
stores parameters and local variables in an area
of memory, known as _______, which stores
elements in last-in first-out fashion.
A. a heap
B. storage area
C. a stack
D. an array
Your answer A is incorrect
The correct answer is C
Sections 6.4 void vs. Value-Returning Methods
6.8 Which of the following should be defined as
a void method?
A. Write a method that prints
integers from 1 to 100.
B. Write a method that returns a
random integer from 1 to 100.
C. Write a method that checks
whether a number is from 1 to
[Link] 4/16
11/21/24, 1:55 AM Introduction to Java Programming
100.
D. Write a method that converts
an uppercase letter to
lowercase.
Your answer is correct
6.9 You should fill in the blank in the following
code with ______________.
public class Test {
public static void main(String[] args)
{
[Link]("The grade is ");
printGrade(78.5);
[Link]("The grade is ");
printGrade(59.5);
}
public static __________
printGrade(double score) {
if (score >= 90.0) {
[Link]('A');
}
else if (score >= 80.0) {
[Link]('B');
}
else if (score >= 70.0) {
[Link]('C');
}
else if (score >= 60.0) {
[Link]('D');
}
else {
[Link]('F');
}
}
}
A. int
B. double
C. boolean
[Link] 5/16
11/21/24, 1:55 AM Introduction to Java Programming
D. char
E. void
Your answer A is incorrect
The correct answer is E
Explanation: void should here because the
method does not return any value.
6.10 You should fill in the blank in the following
code with ______________.
public class Test {
public static void main(String[] args)
{
[Link]("The grade is " +
getGrade(78.5));
[Link]("\nThe grade is " +
getGrade(59.5));
}
public static _________
getGrade(double score) {
if (score >= 90.0)
return 'A';
else if (score >= 80.0)
return 'B';
else if (score >= 70.0)
return 'C';
else if (score >= 60.0)
return 'D';
else
return 'F';
}
}
A. int
B. double
C. boolean
D. char
E. void
[Link] 6/16
11/21/24, 1:55 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is D
Explanation: char should be placed here
because the method returns a character.
6.11 Consider the following incomplete code:
public class Test {
public static void main(String[] args)
{
[Link](f(5));
}
public static int f(int number) {
// Missing body
}
}
The missing method body should be ________.
A. return "number";
B. [Link](number);
C. [Link]("number");
D. return number;
Your answer A is incorrect
The correct answer is D
Sections 6.5 Passing Parameters by Values
6.12 When you invoke a method with a
parameter, the value of the argument is passed
to the parameter. This is referred to as
_________.
A. method invocation
B. pass by value
C. pass by reference
[Link] 7/16
11/21/24, 1:55 AM Introduction to Java Programming
D. pass by name
Your answer A is incorrect
The correct answer is B
6.13 Given the following method, what is the
output of the call nPrint('a', 4)?
static void nPrint(String message, int n) {
while (n > 0) {
[Link](message);
n--;
}
}
A. aaaaa
B. aaaa
C. aaa
D. invalid call
Your answer A is incorrect
The correct answer is D
Explanation: Invalid call because char 'a'
cannot be passed to string message
6.14 Given the following method
static void nPrint(String message, int n) {
while (n > 0) {
[Link](message);
n--;
}
}
What is k after invoking nPrint("A message", k)?
int k = 2;
[Link] 8/16
11/21/24, 1:55 AM Introduction to Java Programming
nPrint("A message", k);
A. 0
B. 1
C. 2
D. 3
Your answer A is incorrect
The correct answer is C
Section 6.8 Overloading Methods
6.15 Analyze the following code:
public class Test {
public static void main(String[] args)
{
[Link](xMethod(5,
500L));
}
public static int xMethod(int n, long
l) {
[Link]("int, long");
return n;
}
public static long xMethod(long n,
long l) {
[Link]("long, long");
return n;
}
}
A. The program displays int,
long followed by 5.
B. The program displays long,
long followed by 5.
C. The program runs fine but
displays things other than 5.
[Link] 9/16
11/21/24, 1:55 AM Introduction to Java Programming
D. The program does not compile
because the compiler cannot
distinguish which xmethod to
invoke.
Your answer is correct
6.16 Analyze the following code:
class Test {
public static void main(String[] args)
{
[Link](xmethod(5));
}
public static int xmethod(int n, long
t) {
[Link]("int");
return n;
}
public static long xmethod(long n) {
[Link]("long");
return n;
}
}
A. The program displays int
followed by 5.
B. The program displays long
followed by 5.
C. The program runs fine but
displays things other than 5.
D. The program does not compile
because the compiler cannot
distinguish which xmethod to
invoke.
Your answer A is incorrect
The correct answer is B
[Link] 10/16
11/21/24, 1:55 AM Introduction to Java Programming
6.17 Analyze the following code.
public class Test {
public static void main(String[] args)
{
[Link](max(1, 2));
}
public static double max(int num1,
double num2) {
[Link]("max(int, double)
is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1,
int num2) {
[Link]("max(double, int)
is invoked");
if (num1 > num2)
return num1;
else
return num2;
}
}
A. The program cannot compile
because you cannot have the
print statement in a non-void
method.
B. The program cannot compile
because the compiler cannot
determine which max method
should be invoked.
C. The program runs and prints 2
followed by "max(int, double)"
[Link] 11/16
11/21/24, 1:55 AM Introduction to Java Programming
is invoked.
D. The program runs and prints 2
followed by "max(double, int)"
is invoked.
E. The program runs and prints
"max(int, double) is invoked"
followed by 2.
Your answer A is incorrect
The correct answer is B
Explanation: This is known as ambiguous
method invocation.
6.18 Analyze the following code.
public class Test {
public static void main(String[] args)
{
[Link](m(2));
}
public static int m(int num) {
return num;
}
public static void m(int num) {
[Link](num);
}
}
A. The program has a compile
error because the two methods
m have the same signature.
B. The program has a compile
error because the second m
method is defined, but not
invoked in the main method.
C. The program runs and prints 2
once.
[Link] 12/16
11/21/24, 1:55 AM Introduction to Java Programming
D. The program runs and prints 2
twice.
Your answer is correct
Explanation: You cannot override the methods
based on the type returned.
Section 6.9 The Scope of Variables
6.19 A variable defined inside a method is
referred to as __________.
A. a global variable
B. a method variable
C. a block variable
D. a local variable
Your answer A is incorrect
The correct answer is D
6.20 What is k after the following block
executes?
{
int k = 2;
nPrint("A message", k);
}
[Link](k);
A. 0
B. 1
C. 2
D. k is not defined outside the
block. So, the program has a
compile error
Your answer A is incorrect
The correct answer is D
[Link] 13/16
11/21/24, 1:55 AM Introduction to Java Programming
Explanation: k is defined inside the block.
Outside the block, k is not defined.
Section 6.10 Case Study: Generating Random
Characters
6.21 (int)([Link]() * (65535 + 1)) returns
a random number __________.
A. between 1 and 65536
B. between 1 and 65535
C. between 0 and 65535
D. between 0 and 65536
Your answer A is incorrect
The correct answer is C
6.22 (int)('a' + [Link]() * ('z' - 'a' + 1))
returns a random number __________.
A. between 0 and (int)'z'
B. between (int)'a' and (int)'z'
C. between 'a' and 'z'
D. between 'a' and 'y'
Your answer A is incorrect
The correct answer is B
6.23 (char)('a' + [Link]() * ('z' - 'a' + 1))
returns a random character __________.
A. between 'a' and 'z'
B. between 'a' and 'y'
C. between 'b' and 'z'
D. between 'b' and 'y'
Your answer is correct
[Link] 14/16
11/21/24, 1:55 AM Introduction to Java Programming
6.24 Which of the following is the best for
generating random integer 0 or 1?
A. (int)[Link]()
B. (int)[Link]() + 1
C. (int)([Link]() + 0.5)
D. (int)([Link]() + 0.2)
E. (int)([Link]() + 0.8)
Your answer A is incorrect
The correct answer is C
Section 6.11 Method Abstraction and Stepwise
Refinement
6.25 The client can use a method without
knowing how it is implemented. The details of
the implementation are encapsulated in the
method and hidden from the client who
invokes the method. This is known as
__________.
A. information hiding
B. encapsulation
C. method hiding
D. simplifying method
Your answer A is incorrect
The correct answer is AB
6.26 __________ is to implement one method in
the structure chart at a time from the top to the
bottom.
A. Bottom-up approach
B. Top-down approach
C. Bottom-up and top-down
approach
[Link] 15/16
11/21/24, 1:55 AM Introduction to Java Programming
D. Stepwise refinement
Your answer A is incorrect
The correct answer is B
6.27 __________ is a simple but incomplete
version of a method.
A. A stub
B. A main method
C. A non-main method
D. A method developed using top-
down approach
Your answer is correct
[Link] 16/16
11/21/24, 1:58 AM Introduction to Java Programming
Introduction to Java Programming, Includes Data Structures, Eleventh Edition, Y. Daniel
Liang
This quiz is for students to practice. A large number of
additional quiz is available for instructors using Quiz
Generator from the Instructor's Resource Website. Videos for
Java, Python, and C++ can be found at
[Link]
Chapter 7 Single-Dimensional Arrays
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book
and edition you are using. Thanks!
Sections 7.2 Array Basics
7.1 What is the representation of the third
element in an array called a?
A. a[2]
B. a(2)
C. a[3]
D. a(3)
Your answer is correct
7.2 If you declare an array double[] list = {3.4,
2.0, 3.5, 5.5}, list[1] is ________.
A. 3.4
B. 2.0
[Link] 1/30
11/21/24, 1:58 AM Introduction to Java Programming
C. 3.5
D. 5.5
E. undefined
Your answer A is incorrect
The correct answer is B
7.3 Which of the following are incorrect?
A. int[] a = new int[2];
B. int a[] = new int[2];
C. int[] a = new int(2);
D. int a = new int[2];
E. int a() = new int[2];
Your answer A is incorrect
The correct answer is CDE
7.4 If you declare an array double[] list = {3.4,
2.0, 3.5, 5.5}, the highest index in array list is
__________.
A. 0
B. 1
C. 2
D. 3
E. 4
Your answer A is incorrect
The correct answer is D
7.5 How many elements are in array double[] list
= new double[5]?
A. 4
B. 5
C. 6
[Link] 2/30
11/21/24, 1:58 AM Introduction to Java Programming
D. 0
Your answer A is incorrect
The correct answer is B
7.6 What is the correct term for numbers[99]?
A. index
B. index variable
C. indexed variable
D. array variable
E. array
Your answer A is incorrect
The correct answer is C
Section 7.3 Case Study: Analyzing Numbers
7.7 Suppose int i = 5, which of the following can
be used as an index for array double[] t = new
double[100]?
A. i
B. (int)([Link]() * 100))
C. i + 10
D. i + 6.5
E. [Link]() * 100
Your answer A is incorrect
The correct answer is ABC
7.8 Analyze the following code.
public class Test {
public static void main(String[] args)
{
int[] x = new int[3];
[Link] 3/30
11/21/24, 1:58 AM Introduction to Java Programming
[Link]("x[0] is " +
x[0]);
}
}
A. The program has a compile
error because the size of the
array wasn't specified when
declaring the array.
B. The program has a runtime
error because the array
elements are not initialized.
C. The program runs fine and
displays x[0] is 0.
D. The program has a runtime
error because the array
element x[0] is not defined.
Your answer A is incorrect
The correct answer is C
7.9 Which of the following statements are valid?
A. int i = new int(30);
B. double d[] = new double[30];
C. int[] i = {3, 4, 3, 2};
D. char[] c = new char();
E. char[] c = new char[4]{'a',
'b', 'c', 'd'};
Your answer A is incorrect
The correct answer is BC
Explanation: e would be corrected if it is char[]
c = new char[]{'a', 'b', 'c', 'd'};
7.10 How can you initialize an array of two
characters to 'a' and 'b'?
[Link] 4/30
11/21/24, 1:58 AM Introduction to Java Programming
A. char[] charArray = new
char[2]; charArray = {'a',
'b'};
B. char[2] charArray = {'a',
'b'};
C. char[] charArray = {'a', 'b'};
D. char[] charArray = new char[]
{'a', 'b'};
Your answer A is incorrect
The correct answer is CD
7.11 What would be the result of attempting to
compile and run the following code?
public class Test {
public static void main(String[] args)
{
double[] x = new double[]{1, 2, 3};
[Link]("Value is " +
x[1]);
}
}
A. The program has a compile
error because the syntax new
double[]{1, 2, 3} is wrong and
it should be replaced by {1,
2, 3}.
B. The program has a compile
error because the syntax new
double[]{1, 2, 3} is wrong and
it should be replaced by new
double[3]{1, 2, 3};
C. The program has a compile
error because the syntax new
double[]{1, 2, 3} is wrong and
it should be replaced by new
double[]{1.0, 2.0, 3.0};
[Link] 5/30
11/21/24, 1:58 AM Introduction to Java Programming
D. The program compiles and runs
fine and the output "Value is
1.0" is printed.
E. The program compiles and runs
fine and the output "Value is
2.0" is printed.
Your answer A is incorrect
The correct answer is E
Explanation: new double[]{1, 2, 3} is correct.
This is the syntax I have not covered in this
edition, but will be covered in the future
edition. In this question, double[] x = new
double[]{1, 2, 3} is equivalent to double[] x =
{1, 2, 3};
Section 7.4 Case Study: Deck of Cards
7.12 Assume int[] t = {1, 2, 3, 4}. What is
[Link]?
A. 0
B. 3
C. 4
D. 5
Your answer A is incorrect
The correct answer is C
7.13 What is the output of the following code?
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
[Link] 6/30
11/21/24, 1:58 AM Introduction to Java Programming
}
[Link](indexOfMax);
A. 0
B. 1
C. 2
D. 3
E. 4
Your answer A is incorrect
The correct answer is B
7.14 Analyze the following code:
public class Test {
public static void main(String[] args)
{
int[] x = new int[5];
int i;
for (i = 0; i < [Link]; i++)
x[i] = i;
[Link](x[i]);
}
}
A. The program displays 0 1 2 3
4.
B. The program displays 4.
C. The program has a runtime
error because the last
statement in the main method
causes
ArrayIndexOutOfBoundsException.
D. The program has a compile
error because i is not defined
in the last statement in the
main method.
Your answer A is incorrect
[Link] 7/30
11/21/24, 1:58 AM Introduction to Java Programming
The correct answer is C
Explanation: After the for loop i is 5. x[5] is
out of bounds.
7.15 Analyze the following code:
public class Test {
public static void main(String[] args)
{
double[] x = {2.5, 3, 4};
for (double value: x)
[Link](value + " ");
}
}
A. The program displays 2.5, 3,
4
B. The program displays 2.5 3 4
C. The program displays 2.5 3.0
4.0
D. The program displays 2.5, 3.0
4.0
E. The program has a syntax error
because value is undefined.
Your answer A is incorrect
The correct answer is C
7.16 What is the output of the following code?
int[] myList = {1, 2, 3, 4, 5, 6};
for (int i = [Link] -
2; i >= 0; i--) {
myList[i + 1] = myList[i];
}
for (int e: myList)
[Link](e + " ");
[Link] 8/30
11/21/24, 1:58 AM Introduction to Java Programming
A. 1 2 3 4 5 6
B. 6 1 2 3 4 5
C. 6 2 3 4 5 1
D. 1 1 2 3 4 5
E. 2 3 4 5 6 1
Your answer A is incorrect
The correct answer is D
7.17 What is output of the following code:
public class Test {
public static void main(String[] args)
{
int[] x = {120, 200, 016};
for (int i = 0; i < [Link]; i++)
[Link](x[i] + " ");
}
}
A. 120 200 16
B. 120 200 14
C. 120 200 20
D. 016 is a compile error. It
should be written as 16.
Your answer A is incorrect
The correct answer is B
Explanation: 016 is an octal number. The
prefix 0 indicates that a number is in octal.
7.18 What is output of the following code:
public class Test {
public static void main(String[] args)
{
int list[] = {1, 2, 3, 4, 5, 6};
for (int i = 1; i < [Link];
[Link] 9/30
11/21/24, 1:58 AM Introduction to Java Programming
i++)
list[i] = list[i - 1];
for (int i = 0; i < [Link];
i++)
[Link](list[i] + " ");
}
}
A. 1 2 3 4 5 6
B. 2 3 4 5 6 6
C. 2 3 4 5 6 1
D. 1 1 1 1 1 1
Your answer A is incorrect
The correct answer is D
7.19 Which of the following is correct?
A. String[] list = new
String{"red", "yellow",
"green"};
B. String[] list = new String[]
{"red", "yellow", "green"};
C. String[] list = {"red",
"yellow", "green"};
D. String list = {"red",
"yellow", "green"};
E. String list = new
String{"red", "yellow",
"green"};
Your answer A is incorrect
The correct answer is BC
Section 7.5 Copying Arrays
7.20 In the following code, what is the output for
list2?
[Link] 10/30
11/21/24, 1:58 AM Introduction to Java Programming
public class Test {
public static void main(String[] args)
{
int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
list2 = list1;
list1[0] = 0; list1[1] = 1; list2[2]
= 2;
for (int i = 0; i < [Link];
i++)
[Link](list2[i] + " ");
}
}
A. 1 2 3
B. 1 1 1
C. 0 1 2
D. 0 1 3
Your answer A is incorrect
The correct answer is C
7.21 In the following code, what is the output for
list1?
public class Test {
public static void main(String[] args)
{
int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
list2 = list1;
list1[0] = 0; list1[1] = 1; list2[2]
= 2;
for (int i = 0; i < [Link];
i++)
[Link](list1[i] + " ");
}
}
[Link] 11/30
11/21/24, 1:58 AM Introduction to Java Programming
A. 1 2 3
B. 1 1 1
C. 0 1 2
D. 0 1 3
Your answer A is incorrect
The correct answer is C
7.22 Analyze the following code:
public class Test {
public static void main(String[] args)
{
int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for (int i = 0; i < [Link]; i++)
[Link](y[i] + " ");
}
}
A. The program displays 1 2 3 4
B. The program displays 0 0
C. The program displays 0 0 3 4
D. The program displays 0 0 0 0
Your answer is correct
7.23 Analyze the following code:
public class Test {
public static void main(String[] args)
{
int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for (int i = 0; i < [Link]; i++)
[Link] 12/30
11/21/24, 1:58 AM Introduction to Java Programming
[Link](x[i] + " ");
}
}
A. The program displays 1 2 3 4
B. The program displays 0 0
C. The program displays 0 0 3 4
D. The program displays 0 0 0 0
Your answer A is incorrect
The correct answer is B
7.24 Analyze the following code:
public class Test {
public static void main(String[] args)
{
final int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for (int i = 0; i < [Link]; i++)
[Link](y[i] + " ");
}
}
A. The program displays 1 2 3 4.
B. The program displays 0 0.
C. The program has a compile
error on the statement x = new
int[2], because x is final and
cannot be changed.
D. The elements in the array x
cannot be changed, because x
is final.
Your answer A is incorrect
The correct answer is C
[Link] 13/30
11/21/24, 1:58 AM Introduction to Java Programming
Explanation: The value stored in x is final, but
the values in the array are not final. x is a
constant reference variable that points to an
array with four elements Because it is a
constant, you cannot create a new reference
variable x that points to a different array, but
you can change the value of the elements in the
array, e.g. x[1] could be changed to 10 instead
of 2.
7.25 Analyze the following code.
int[] list = new int[5];
list = new int[6];
A. The code has compile errors
because the variable list
cannot be changed once it is
assigned.
B. The code has runtime errors
because the variable list
cannot be changed once it is
assigned.
C. The code can compile and run
fine. The second line assigns
a new array to list.
D. The code has compile errors
because you cannot assign a
different size array to list.
Your answer A is incorrect
The correct answer is C
7.26 Analyze the following code:
public class Test {
public static void main(String[] args)
{
[Link] 14/30
11/21/24, 1:58 AM Introduction to Java Programming
int[] a = new int[4];
a[1] = 1;
a = new int[2];
[Link]("a[1] is " +
a[1]);
}
}
A. The program has a compile
error because new int[2] is
assigned to a.
B. The program has a runtime
error because a[1] is not
initialized.
C. The program displays a[1] is
0.
D. The program displays a[1] is
1.
Your answer A is incorrect
The correct answer is C
Explanation: After executing the statement a =
new int[2], a refers to int[2]. The default value
for a[0] and a[1] is 0.
7.27 The __________ method copies the
sourceArray to the targetArray.
A.
[Link](sourceArray,
0, targetArray, 0,
[Link]);
B.
[Link](sourceArray,
0, targetArray, 0,
[Link]);
C. [Link](sourceArray,
0, targetArray, 0,
[Link]);
[Link] 15/30
11/21/24, 1:58 AM Introduction to Java Programming
D. [Link](sourceArray,
0, targetArray, 0,
[Link]);
Your answer A is incorrect
The correct answer is D
Section 7.6 Passing Arrays to Methods
7.28 When you pass an array to a method, the
method receives __________.
A. a copy of the array
B. a copy of the first element
C. the reference of the array
D. the length of the array
Your answer A is incorrect
The correct answer is C
7.29 Show the output of the following code:
public class Test {
public static void main(String[] args)
{
int[] x = {1, 2, 3, 4, 5};
increase(x);
int[] y = {1, 2, 3, 4, 5};
increase(y[0]);
[Link](x[0] + " " +
y[0]);
}
public static void increase(int[] x) {
for (int i = 0; i < [Link]; i++)
x[i]++;
}
[Link] 16/30
11/21/24, 1:58 AM Introduction to Java Programming
public static void increase(int y) {
y++;
}
}
A. 0 0
B. 1 1
C. 2 2
D. 2 1
E. 1 2
Your answer A is incorrect
The correct answer is D
Explanation: Invoking increase(x) passes the
reference of the array to the method. Invoking
increase(y[0]) passes the value 1 to the method.
The value y[0] outside the method is not
changed.
7.30 Do the following two programs produce the
same result?
Program I:
public class Test {
public static void main(String[] args)
{
int[] list = {1, 2, 3, 4, 5};
reverse(list);
for (int i = 0; i < [Link];
i++)
[Link](list[i] + " ");
}
public static void reverse(int[] list)
{
int[] newList = new
int[[Link]];
for (int i = 0; i < [Link];
i++)
newList[i] = list[[Link] - 1
[Link] 17/30
11/21/24, 1:58 AM Introduction to Java Programming
- i];
list = newList;
}
}
Program II:
public class Test {
public static void main(String[] args)
{
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < [Link];
i++)
[Link](oldList[i] + "
");
}
public static void reverse(int[] list)
{
int[] newList = new
int[[Link]];
for (int i = 0; i < [Link];
i++)
newList[i] = list[[Link] - 1
- i];
list = newList;
}
}
A. Yes
B. No
Your answer is correct
7.31 Analyze the following code:
public class Test {
public static void main(String[] args)
{
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
[Link] 18/30
11/21/24, 1:58 AM Introduction to Java Programming
for (int i = 0; i < [Link];
i++)
[Link](oldList[i] + "
");
}
public static void reverse(int[] list)
{
int[] newList = new
int[[Link]];
for (int i = 0; i < [Link];
i++)
newList[i] = list[[Link] - 1
- i];
list = newList;
}
}
A. The program displays 1 2 3 4
5.
B. The program displays 1 2 3 4
5 and then raises an
ArrayIndexOutOfBoundsException.
C. The program displays 5 4 3 2
1.
D. The program displays 5 4 3 2
1 and then raises an
ArrayIndexOutOfBoundsException.
Your answer is correct
Explanation: The contents of the array oldList
have not been changed as result of invoking the
reverse method.
7.32 Analyze the following code:
public class Test1 {
public static void main(String[] args)
{
[Link] 19/30
11/21/24, 1:58 AM Introduction to Java Programming
xMethod(new double[]{3, 3});
xMethod(new double[5]);
xMethod(new double[3]{1, 2, 3});
}
public static void xMethod(double[] a)
{
[Link]([Link]);
}
}
A. The program has a compile
error because xMethod(new
double[]{3, 3}) is incorrect.
B. The program has a compile
error because xMethod(new
double[5]) is incorrect.
C. The program has a compile
error because xMethod(new
double[3]{1, 2, 3}) is
incorrect.
D. The program has a runtime
error because a is null.
Your answer A is incorrect
The correct answer is C
Explanation: new double[3]{1, 2, 3} should be
replaced by new double[]{1, 2, 3})
(anonymous array).
7.33 The JVM stores the array in an area of
memory, called _______, which is used for
dynamic memory allocation where blocks of
memory are allocated and freed in an arbitrary
order.
A. stack
B. heap
C. memory block
[Link] 20/30
11/21/24, 1:58 AM Introduction to Java Programming
D. dynamic memory
Your answer A is incorrect
The correct answer is B
Section 7.7 Returning an Array from a Method
7.34 When you return an array from a method,
the method returns __________.
A. a copy of the array
B. a copy of the first element
C. the reference of the array
D. the length of the array
Your answer A is incorrect
The correct answer is C
7.35 Suppose a method p has the following
heading:
public static int[] p()
What return statement may be used in p()?
A. return 1;
B. return {1, 2, 3};
C. return int[]{1, 2, 3};
D. return new int[]{1, 2, 3};
Your answer A is incorrect
The correct answer is D
7.36 The reverse method is defined in the
textbook. What is list1 after executing the
following statements?
[Link] 21/30
11/21/24, 1:58 AM Introduction to Java Programming
int[] list1 = {1, 2, 3, 4, 5, 6};
list1 = reverse(list1);
A. list1 is 1 2 3 4 5 6
B. list1 is 6 5 4 3 2 1
C. list1 is 0 0 0 0 0 0
D. list1 is 6 6 6 6 6 6
Your answer A is incorrect
The correct answer is B
7.37 The reverse method is defined in this
section. What is list1 after executing the
following statements?
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
A. list1 is 1 2 3 4 5 6
B. list1 is 6 5 4 3 2 1
C. list1 is 0 0 0 0 0 0
D. list1 is 6 6 6 6 6 6
Your answer is correct
Section 7.9 Variable-Length Argument Lists
7.38 Which of the following declarations are
correct?
A. public static void
print(String... strings,
double... numbers)
B. public static void
print(double... numbers,
String name)
C. public static double...
print(double d1, double d2)
D. public static void
print(double... numbers)
[Link] 22/30
11/21/24, 1:58 AM Introduction to Java Programming
E. public static void print(int
n, double... numbers)
Your answer A is incorrect
The correct answer is DE
Explanation: Only one variable-length
parameter may be specified in a method and
this parameter must be the last parameter. The
method return type cannot be a variable-length
parameter.
7.39 Which of the following statements are
correct to invoke the printMax method in
Listing 7.5 in the textbook?
A. printMax(1, 2, 2, 1, 4);
B. printMax(new double[]{1, 2,
3});
C. printMax(1.0, 2.0, 2.0, 1.0,
4.0);
D. printMax(new int[]{1, 2, 3});
Your answer A is incorrect
The correct answer is ABC
Explanation: The last one printMax(new int[]
{1, 2, 3}); is incorrect, because the array must
of the double[] type.
Section 7.10 Searching Arrays
7.40 For the binarySearch method in Section
7.10.2, what is low and high after the first
iteration of the while loop when invoking
binarySearch(new int[]{1, 4, 6, 8, 10, 15, 20},
11)?
A. low is 0 and high is 6
[Link] 23/30
11/21/24, 1:58 AM Introduction to Java Programming
B. low is 5 and high is 5
C. low is 3 and high is 6
D. low is 4 and high is 6
E. low is 6 and high is 5
Your answer A is incorrect
The correct answer is D
7.41 If a key is not in the list, the binarySearch
method returns _________.
A. insertion point
B. insertion point - 1
C. -(insertion point + 1)
D. -insertion point
Your answer A is incorrect
The correct answer is C
Section 7.11 Sorting Arrays
7.42 Use the selectionSort method presented in
this section to answer this question. Assume
list is {3.1, 3.1, 2.5, 6.4, 2.1}, what is the
content of list after the first iteration of the
outer loop in the method?
A. 3.1, 3.1, 2.5, 6.4, 2.1
B. 2.5, 3.1, 3.1, 6.4, 2.1
C. 2.1, 2.5, 3.1, 3.1, 6.4
D. 3.1, 3.1, 2.5, 2.1, 6.4
E. 2.1, 3.1, 2.5, 6.4, 3.1
Your answer A is incorrect
The correct answer is E
[Link] 24/30
11/21/24, 1:58 AM Introduction to Java Programming
7.43 Use the selectionSort method presented in
this section to answer this question. What is
list1 after executing the following statements?
double[] list1 = {3.1, 3.1, 2.5, 6.4};
selectionSort(list1);
A. list1 is 3.1, 3.1, 2.5, 6.4
B. list1 is 2.5, 3.1, 3.1, 6.4
C. list1 is 6.4, 3.1, 3.1, 2.5
D. list1 is 3.1, 2.5, 3.1, 6.4
Your answer A is incorrect
The correct answer is B
Section 7.12 The Arrays Class
7.44 The __________ method sorts the array
scores of the double[] type.
A. [Link](scores)
B.
[Link](scores)
C. [Link](scores)
D.
[Link](scores)
Your answer A is incorrect
The correct answer is C
7.45 Assume int[] scores = {1, 20, 30, 40, 50},
what value does
[Link](scores, 30)
return?
A. 0
B. -1
C. 1
[Link] 25/30
11/21/24, 1:58 AM Introduction to Java Programming
D. 2
E. -2
Your answer A is incorrect
The correct answer is D
7.46 Assume int[] scores = {1, 20, 30, 40, 50},
what value does
[Link](scores, 3) return?
A. 0
B. -1
C. 1
D. 2
E. -2
Your answer A is incorrect
The correct answer is E
Explanation: The binarySearch method returns
the index of the search key if it is contained in
the list. Otherwise, it returns -insertionPoint -
1. The insertion point is the point at which the
key would be inserted into the list. In this case
the insertion point is 1. Note that the array
index starts from 0.
7.47 Assume int[] scores = {1, 20, 30, 40, 50},
what is the output of
[Link]([Link](scores))?
A. {1, 20, 30, 40, 50}
B. [1, 20, 30, 40, 50]
C. {1 20 30 40 50}
D. [1 20 30 40 50]
Your answer A is incorrect
The correct answer is B
[Link] 26/30
11/21/24, 1:58 AM Introduction to Java Programming
Section 7.13 Command-Line Arguments
7.48 How can you get the word "abc" in the
main method from the following call?
java Test "+" 3 "abc" 2
A. args[0]
B. args[1]
C. args[2]
D. args[3]
Your answer A is incorrect
The correct answer is C
7.49 Given the following program:
public class Test {
public static void main(String[] args)
{
for (int i = 0; i < [Link];
i++) {
[Link](args[i] + " ");
}
}
}
What is the output, if you run the program using
java Test 1 2 3
A. 3
B. 1
C. 1 2 3
D. 1 2
Your answer A is incorrect
The correct answer is C
[Link] 27/30
11/21/24, 1:58 AM Introduction to Java Programming
7.50 Which code fragment would correctly
identify the number of arguments passed via
the command line to a Java application,
excluding the name of the class that is being
invoked?
A. int count = [Link];
B. int count = [Link] - 1;
C. int count = 0; while
(args[count] != null) count
++;
D. int count=0; while (!
(args[count].equals("")))
count ++;
Your answer is correct
7.51 Which correctly creates an array of five
empty Strings?
A. String[] a = new String [5];
B. String[] a = {"", "", "", "",
""};
C. String[5] a;
D. String[ ] a = new String [5];
for (int i = 0; i < 5; a[i++]
= null);
Your answer A is incorrect
The correct answer is B
7.52 Analyze the following code:
public class Test {
public static void main(String argv[])
{
[Link]("[Link] is "
+ [Link]);
[Link] 28/30
11/21/24, 1:58 AM Introduction to Java Programming
}
}
A. The program has a compile
error because String argv[] is
wrong and it should be
replaced by String[] args.
B. The program has a compile
error because String argv[] is
wrong and it should be
replaced by String args[].
C. If you run this program
without passing any arguments,
the program would have a
runtime error because argv is
null.
D. If you run this program
without passing any arguments,
the program would display
[Link] is 0.
Your answer A is incorrect
The correct answer is D
Explanation: The parameter for the main
method is an array of String. The declaration
String argv[] is correct. When you run the
program without passing arguments, argv is
new String[0]. Thus, [Link] is 0. See the
NOTE box in the section, 'Passing Arguments
to Java Programs.'
7.53 Which of the following is the correct header
of the main method?
A. public static void
main(String[] args)
B. public static void main(String
args[])
[Link] 29/30
11/21/24, 1:58 AM Introduction to Java Programming
C. public static void
main(String[] x)
D. public static void
main(String x[])
E. static void main(String[]
args)
Your answer A is incorrect
The correct answer is ABCD
Explanation: e is incorrect because the main
method must be public.
[Link] 30/30
11/21/24, 2:01 AM Introduction to Java Programming
Introduction to Java Programming, Includes Data Structures, Eleventh Edition, Y. Daniel
Liang
This quiz is for students to practice. A large number of
additional quiz is available for instructors using Quiz
Generator from the Instructor's Resource Website. Videos for
Java, Python, and C++ can be found at
[Link]
Chapter 8 Multidimensional Arrays
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book
and edition you are using. Thanks!
Section 8.2 Two-Dimensional Array Basics
8.1 Which of the following statements are
correct?
A. char[][] charArray = {'a',
'b'};
B. char[2][2] charArray = {{'a',
'b'}, {'c', 'd'}};
C. char[2][] charArray = {{'a',
'b'}, {'c', 'd'}};
D. char[][] charArray = {{'a',
'b'}, {'c', 'd'}};
Your answer A is incorrect
The correct answer is D
[Link] 1/11
11/21/24, 2:01 AM Introduction to Java Programming
8.2 Assume double[][] x = new double[4][5],
what are [Link] and x[2].length?
A. 4 and 4
B. 4 and 5
C. 5 and 4
D. 5 and 5
Your answer A is incorrect
The correct answer is B
8.3 What is the index variable for the element at
the first row and first column in array a?
A. a[0][0]
B. a[1][1]
C. a[0][1]
D. a[1][0]
Your answer is correct
8.4 When you create an array using the following
statement, the element values are automatically
initialized to 0.
int[][] matrix = new int[5][5];
A. True
B. False
Your answer is correct
8.5 How many elements are in array matrix (int[]
[] matrix = new int[5][5])?
A. 14
B. 20
C. 25
[Link] 2/11
11/21/24, 2:01 AM Introduction to Java Programming
D. 30
Your answer A is incorrect
The correct answer is C
8.6 Analyze the following code:
public class Test {
public static void main(String[] args)
{
boolean[][] x = new boolean[3][];
x[0] = new boolean[1]; x[1] = new
boolean[2];
x[2] = new boolean[3];
[Link]("x[2][2] is " +
x[2][2]);
}
}
A. The program has a compile
error because new boolean[3][]
is wrong.
B. The program has a runtime
error because x[2][2] is null.
C. The program runs and displays
x[2][2] is null.
D. The program runs and displays
x[2][2] is true.
E. The program runs and displays
x[2][2] is false.
Your answer A is incorrect
The correct answer is E
Explanation: x is a ragged array. (See the
section on Ragged Array) x[2] has three
elements with default value false.
[Link] 3/11
11/21/24, 2:01 AM Introduction to Java Programming
8.7 Assume int[][] x = {{1, 2}, {3, 4}, {5, 6}},
what are [Link] are x[0].length?
A. 2 and 1
B. 2 and 2
C. 3 and 2
D. 2 and 3
E. 3 and 3
Your answer A is incorrect
The correct answer is C
8.8 Assume int[][] x = {{1, 2}, {3, 4, 5}, {5, 6, 5,
9}}, what are x[0].length, x[1].length, and
x[2].length?
A. 2, 3, and 3
B. 2, 3, and 4
C. 3, 3, and 3
D. 3, 3, and 4
E. 2, 2, and 2
Your answer A is incorrect
The correct answer is B
Section 8.3 Processing Two-Dimensional Arrays
8.9 What is the output of the following program?
public class Test {
public static void main(String[] args)
{
int[][] values = {{3, 4, 5, 1}, {33,
6, 1, 2}};
int v = values[0][0];
for (int row = 0; row <
[Link]; row++)
for (int column = 0; column <
[Link] 4/11
11/21/24, 2:01 AM Introduction to Java Programming
values[row].length; column++)
if (v < values[row][column])
v = values[row][column];
[Link](v);
}
}
A. 1
B. 3
C. 5
D. 6
E. 33
Your answer A is incorrect
The correct answer is E
8.10 What is the output of the following
program?
public class Test {
public static void main(String[] args)
{
int[][] values = {{3, 4, 5, 1}, {33,
6, 1, 2}};
int v = values[0][0];
for (int[] list : values)
for (int element : list)
if (v > element)
v = element;
[Link](v);
}
}
A. 1
B. 3
C. 5
D. 6
[Link] 5/11
11/21/24, 2:01 AM Introduction to Java Programming
E. 33
Your answer is correct
8.11 What is the output of the following
program?
public class Test {
public static void main(String[] args)
{
int[][] values = {{3, 4, 5, 1 },
{33, 6, 1, 2}};
for (int row = 0; row <
[Link]; row++) {
[Link](values[row]);
for (int column = 0; column <
values[row].length; column++)
[Link](values[row]
[column] + " ");
[Link]();
}
}
}
A. The program prints two rows 3
4 5 1 followed by 33 6 1 2
B. The program prints on row 3 4
5 1 33 6 1 2
C. The program prints two rows 3
4 5 1 followed by 2 1 6 33
D. The program prints two rows 1
3 4 5 followed by 1 2 6 33
E. The program prints one row 1 3
4 5 1 2 6 33
Your answer A is incorrect
The correct answer is D
[Link] 6/11
11/21/24, 2:01 AM Introduction to Java Programming
8.12 What is the output of the following code?
public class Test {
public static void main(String[] args)
{
int[][] matrix =
{{1, 2, 3, 4},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15}};
for (int i = 0; i < 4; i++)
[Link](matrix[i][1] + "
");
}
}
A. 1 2 3 4
B. 4 5 6 7
C. 1 3 8 12
D. 2 5 9 13
E. 3 6 10 14
Your answer A is incorrect
The correct answer is D
8.13 What is the output of the following code?
public class Test5 {
public static void main(String[] args)
{
int[][] matrix =
{{1, 2, 3, 4},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 13, 14, 15}};
for (int i = 0; i < 4; i++)
[Link](matrix[1][i] + "
");
[Link] 7/11
11/21/24, 2:01 AM Introduction to Java Programming
}
}
A. 1 2 3 4
B. 4 5 6 7
C. 1 3 8 12
D. 2 5 9 13
E. 3 6 10 14
Your answer A is incorrect
The correct answer is B
Section 8.4 Passing Two-Dimensional Arrays to
Methods
8.14 Suppose a method p has the following
heading:
public static int[][] p()
What return statement may be used in p()?
A. return 1;
B. return {1, 2, 3};
C. return int[]{1, 2, 3};
D. return new int[]{1, 2, 3};
E. return new int[][]{{1, 2, 3},
{2, 4, 5}};
Your answer A is incorrect
The correct answer is E
8.15 What is the output of the following
program?
public class Test {
public static void main(String[] args)
{
int[][] values = {{3, 4, 5, 1}, {33,
[Link] 8/11
11/21/24, 2:01 AM Introduction to Java Programming
6, 1, 2}};
for (int row = 0; row <
[Link]; row++) {
[Link](m(values[row]) +
" ");
}
}
public static int m(int[] list) {
int v = list[0];
for (int i = 1; i < [Link];
i++)
if (v < list[i])
v = list[i];
return v;
}
}
A. 3 33
B. 1 1
C. 5 6
D. 5 33
E. 33 5
Your answer A is incorrect
The correct answer is D
Section 8.8 Multidimensional Arrays
8.16 Assume double[][][] x = new double[4][5]
[6], what are [Link], x[2].length, and x[0]
[0].length?
A. 4, 5, and 6
B. 6, 5, and 4
C. 5, 5, and 5
D. 4, 5, and 4
Your answer is correct
[Link] 9/11
11/21/24, 2:01 AM Introduction to Java Programming
8.17 Which of the following statements are
correct?
A. char[][][] charArray = new
char[2][2][];
B. char[2][2][] charArray = {'a',
'b'};
C. char[][][] charArray = {{'a',
'b'}, {'c', 'd'}, {'e', 'f'}};
D. char[][][] charArray =
{{{'a', 'b'}, {'c', 'd'},
{'e', 'f'}}};
Your answer A is incorrect
The correct answer is AD
8.18 What is the output of the following code?
public class Test {
public static void main(String[] args)
{
int[][][] data = {{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}};
[Link](data[1][0][0]);
}
}
A. 1
B. 2
C. 4
D. 5
E. 6
Your answer A is incorrect
The correct answer is D
[Link] 10/11
11/21/24, 2:01 AM Introduction to Java Programming
8.19 What is the output of the following code?
public class Test {
public static void main(String[] args)
{
int[][][] data = {{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}};
[Link](ttt(data[0]));
}
public static int ttt(int[][] m) {
int v = m[0][0];
for (int i = 0; i < [Link]; i++)
for (int j = 0; j < m[i].length;
j++)
if (v < m[i][j])
v = m[i][j];
return v;
}
}
A. 1
B. 2
C. 4
D. 5
E. 6
Your answer A is incorrect
The correct answer is C
[Link] 11/11
11/21/24, 2:04 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of
additional quiz is available for instructors using Quiz
Generator from the Instructor's Resource Website. Videos for
Java, Python, and C++ can be found at
[Link]
Chapter 9 Objects and Classes
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book
and edition you are using. Thanks!
Section 9.2 Defining Classes for Objects
9.1 __________ represents an entity in the real
world that can be distinctly identified.
A. A class
B. An object
C. A method
D. A data field
[Link] 1/33
11/21/24, 2:04 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
9.2 _______ is a construct that defines objects of
the same type.
A. A class
B. An object
C. A method
D. A data field
Your answer is correct
9.3 An object is an instance of a __________.
A. program
B. class
C. method
D. data
Your answer A is incorrect
The correct answer is B
9.4 The keyword __________ is required to
declare a class.
A. public
B. private
C. class
D. All of the above.
Your answer A is incorrect
The correct answer is C
[Link] 2/33
11/21/24, 2:04 AM Introduction to Java Programming
Section 9.4 Constructing Objects Using
Constructors
9.5 ________ is invoked to create an object.
A. A constructor
B. The main method
C. A method with a return type
D. A method with the void return
type
Your answer is correct
9.6 Which of the following statements are true?
A. A default constructor is
provided automatically if no
constructors are explicitly
declared in the class.
B. At least one constructor must
always be defined explicitly.
C. Every class has a default
constructor.
D. The default constructor is a
no-arg constructor.
Your answer A is incorrect
The correct answer is AD
9.7 Which of the following statements are true?
A. Multiple constructors can be
defined in a class.
B. Constructors do not have a
return type, not even void.
C. Constructors must have the
same name as the class itself.
[Link] 3/33
11/21/24, 2:04 AM Introduction to Java Programming
D. Constructors are invoked
using the new operator when an
object is created.
Your answer A is incorrect
The correct answer is ABCD
9.8 Analyze the following code:
public class Test {
public static void main(String[] args)
{
A a = new A();
[Link]();
}
}
class A {
String s;
A(String s) {
this.s = s;
}
void print() {
[Link](s);
}
}
A. The program has a compile
error because class A is not a
public class.
B. The program has a compile
error because class A does not
have a default constructor.
C. The program compiles and runs
fine and prints nothing.
D. The program would compile and
run if you change A a = new
A() to A a = new A("5").
[Link] 4/33
11/21/24, 2:04 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is BD
9.9 Analyze the following code.
class TempClass {
int i;
public void TempClass(int j) {
int i = j;
}
}
public class C {
public static void main(String[] args)
{
TempClass temp = new TempClass(2);
}
}
A. The program has a compile
error because TempClass does
not have a default
constructor.
B. The program has a compile
error because TempClass does
not have a constructor with an
int argument.
C. The program compiles fine,
but it does not run because
class C is not public.
D. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is B
Explanation: The program would be fine if the
void keyword is removed from public void
TempClass(int j).
[Link] 5/33
11/21/24, 2:04 AM Introduction to Java Programming
Section 9.5 Accessing Objects via Reference
Variables
9.10 Given the declaration Circle x = new
Circle(), which of the following statement is
most accurate.
A. x contains an int value.
B. x contains an object of the
Circle type.
C. x contains a reference to a
Circle object.
D. You can assign an int value
to x.
Your answer A is incorrect
The correct answer is C
Explanation: x is a reference variable that can
reference a Circle object or null if it does not
reference any object.
9.11 Analyze the following code.
public class Test {
int x;
public Test(String t) {
[Link]("Test");
}
public static void main(String[] args)
{
Test test = null;
[Link](test.x);
}
}
A. The program has a compile
error because test is not
[Link] 6/33
11/21/24, 2:04 AM Introduction to Java Programming
initialized.
B. The program has a compile
error because x has not been
initialized.
C. The program has a compile
error because you cannot
create an object from the
class that defines the object.
D. The program has a compile
error because Test does not
have a default constructor.
E. The program has a runtime
NullPointerException because
test is null while executing
test.x.
Your answer A is incorrect
The correct answer is E
9.12 The default value for data field of a boolean
type, numeric type, object type is
___________, respectively.
A. true, 1, Null
B. false, 0, null
C. true, 0, null
D. true, 1, null
E. false, 1, null
Your answer A is incorrect
The correct answer is B
9.13 Which of the following statements are true?
A. Local variables do not have
default values.
[Link] 7/33
11/21/24, 2:04 AM Introduction to Java Programming
B. Data fields have default
values.
C. A variable of a primitive type
holds a value of the primitive
type.
D. A variable of a reference
type holds a reference to
where an object is stored in
the memory.
E. You may assign an int value to
a reference variable.
Your answer A is incorrect
The correct answer is ABCD
9.14 Analyze the following code:
public class Test {
public static void main(String[] args)
{
double radius;
final double PI= 3.15169;
double area = radius * radius * PI;
[Link]("Area is " +
area);
}
}
A. The program has compile
errors because the variable
radius is not initialized.
B. The program has a compile
error because a constant PI is
defined inside a method.
C. The program has no compile
errors but will get a runtime
error because radius is not
initialized.
[Link] 8/33
11/21/24, 2:04 AM Introduction to Java Programming
D. The program compiles and runs
fine.
Your answer is correct
9.15 Analyze the following code.
public class Test {
int x;
public Test(String t) {
[Link]("Test");
}
public static void main(String[] args)
{
Test test = new Test();
[Link](test.x);
}
}
A. The program has a compile
error because
[Link] method
cannot be invoked from the
constructor.
B. The program has a compile
error because x has not been
initialized.
C. The program has a compile
error because you cannot
create an object from the
class that defines the object.
D. The program has a compile
error because Test does not
have a default constructor.
Your answer A is incorrect
The correct answer is D
[Link] 9/33
11/21/24, 2:04 AM Introduction to Java Programming
Explanation: Note that a default no-arg
constructor is provided only if no constructors
are explicitly defined in the class. In this case,
a constructor Test(String t) is already defined.
So, there is no default no-arg constructor in the
Test class.
9.16 Suppose TestCircle and Circle in Listing 9.1
are in two separate files named [Link]
and [Link], respectively. What is the
outcome of compiling [Link] and then
[Link]?
A. Only [Link]
compiles.
B. Only [Link] compiles.
C. Both compile fine.
D. Neither compiles
successfully.
Your answer A is incorrect
The correct answer is C
9.17 Which of the following statements are
correct?
A. A reference variable is an
object.
B. A reference variable
references to an object.
C. A data field in a class must
be of a primitive type.
D. A data field in a class can
be of an object type.
Your answer A is incorrect
The correct answer is BD
[Link] 10/33
11/21/24, 2:04 AM Introduction to Java Programming
Explanation: (a) is wrong because a reference
variable is not an object, it is a reference that
points to an object. (c) is incorrect because a
class may have a data field of an object type
such as String.
Section 9.6 Using Classes From the Java
Library
9.18 Which of the following code A or B, or both
creates an object of the Date class:
A:
public class Test {
public Test() {
new [Link]();
}
}
B:
public class Test {
public Test() {
[Link] date = new
[Link]();
}
}
A. A.
B. B.
C. Neither
Your answer A is incorrect
The correct answer is AB
Explanation: Both (A) and (B) are fine. In A,
an object is created without explicit reference.
This is known as anonymous object.
9.19 Which of the following statements are
correct?
[Link] 11/33
11/21/24, 2:04 AM Introduction to Java Programming
A. When creating a Random object,
you have to specify the seed
or use the default seed.
B. If two Random objects have the
same seed, the sequence of the
random numbers obtained from
these two objects are
identical.
C. The nextInt() method in the
Random class returns the next
random int value.
D. The nextDouble() method in
the Random class returns the
next random double value.
Your answer A is incorrect
The correct answer is ABCD
9.20 To obtain the distance between the points
(40, 50) and (5.5, 4.4), use _________.
A. distance(40, 50, 5.5, 4.4)
B. new Point2D(40,
50).distance(5.5, 4.4)
C. new Point2D(40,
50).distance(new Point2D(5.5,
4.4))
D. new Point2D(5.5,
4.4).distance(40, 50)
E. new Point2D(5.5,
4.4).distance(new Point2D(40,
50))
Your answer A is incorrect
The correct answer is BCDE
[Link] 12/33
11/21/24, 2:04 AM Introduction to Java Programming
Section 9.7 Static Variables, Constants, and
Methods
9.21 Variables that are shared by every instance
of a class are __________.
A. public variables
B. private variables
C. instance variables
D. class variables
Your answer A is incorrect
The correct answer is D
9.22 You should add the static keyword in the
place of ? in Line ________ in the following
code:
1 public class Test {
2 private int age;
3
4 public ? int square(int n) {
5 return n * n;
6 }
7
8 public ? int getAge() {
9 return age;
10 }
11 }
A. in line 4
B. in line 8
C. in both line 4 and line 8
D. none
Your answer is correct
Explanation: The square method should be
static because it does not reference any
instance data or invoke any instance method.
[Link] 13/33
11/21/24, 2:04 AM Introduction to Java Programming
9.23 A method that is associated with an
individual object is called __________.
A. a static method
B. a class method
C. an instance method
D. an object method
Your answer A is incorrect
The correct answer is C
9.24 To declare a constant MAX_LENGTH as a
member of the class, you write
A. final static MAX_LENGTH =
99.98;
B. final static float MAX_LENGTH
= 99.98;
C. static double MAX_LENGTH =
99.98;
D. final double MAX_LENGTH =
99.98;
E. final static double MAX_LENGTH
= 99.98;
Your answer A is incorrect
The correct answer is E
9.25 Analyze the following code.
public class Test {
public static void main(String[] args)
{
int n = 2;
xMethod(n);
[Link] 14/33
11/21/24, 2:04 AM Introduction to Java Programming
[Link]("n is " + n);
}
void xMethod(int n) {
n++;
}
}
A. The code has a compile error
because xMethod does not
return a value.
B. The code has a compile error
because xMethod is not
declared static.
C. The code prints n is 1.
D. The code prints n is 2.
E. The code prints n is 3.
Your answer A is incorrect
The correct answer is B
9.26 What is the output of the second println
statement in the main method?
public class Foo {
int i;
static int s;
public static void main(String[] args)
{
Foo f1 = new Foo();
[Link]("f1.i is " + f1.i
+ " f1.s is " + f1.s);
Foo f2 = new Foo();
[Link]("f2.i is " + f2.i
+ " f2.s is " + f2.s);
Foo f3 = new Foo();
[Link]("f3.i is " + f3.i
+ " f3.s is " + f3.s);
}
[Link] 15/33
11/21/24, 2:04 AM Introduction to Java Programming
public Foo() {
i++;
s++;
}
}
A. f2.i is 1 f2.s is 1
B. f2.i is 1 f2.s is 2
C. f2.i is 2 f2.s is 2
D. f2.i is 2 f2.s is 1
Your answer A is incorrect
The correct answer is B
Explanation: i is an instance variable and s is
static, shared by all objects of the Foo class.
9.27 What is the output of the third println
statement in the main method?
public class Foo {
int i;
static int s;
public static void main(String[] args)
{
Foo f1 = new Foo();
[Link]("f1.i is " + f1.i
+ " f1.s is " + f1.s);
Foo f2 = new Foo();
[Link]("f2.i is " + f2.i
+ " f2.s is " + f2.s);
Foo f3 = new Foo();
[Link]("f3.i is " + f3.i
+ " f3.s is " + f3.s);
}
public Foo() {
i++;
s++;
}
}
[Link] 16/33
11/21/24, 2:04 AM Introduction to Java Programming
A. f3.i is 1 f3.s is 1
B. f3.i is 1 f3.s is 2
C. f3.i is 1 f3.s is 3
D. f3.i is 3 f3.s is 1
E. f3.i is 3 f3.s is 3
Your answer A is incorrect
The correct answer is C
Explanation: i is an instance variable and s is
static, shared by all objects of the Foo class.
9.28 What code may be filled in the blank
without causing syntax or runtime errors:
public class Test {
[Link] date;
public static void main(String[] args)
{
Test test = new Test();
[Link](_________________);
}
}
A. [Link]
B. date
C. [Link]()
D. [Link]()
Your answer is correct
Explanation: b and d cause compile errors
because date is an instance variable and cannot
be accessed from static context. c is wrong
because [Link] is null, causing
NullPointerException.
9.29 Suppose the xMethod() is invoked in the
following constructor in a class, xMethod() is
[Link] 17/33
11/21/24, 2:04 AM Introduction to Java Programming
_________ in the class.
public MyClass() {
xMethod();
}
A. a static method
B. an instance method
C. a static method or an
instance method
Your answer A is incorrect
The correct answer is C
9.30 Suppose the xMethod() is invoked from a
main method in a class as follows, xMethod()
is _________ in the class.
public static void main(String[] args) {
xMethod();
}
A. a static method
B. an instance method
C. a static method or an
instance method
Your answer is correct
Section 9.8 Visibility Modifiers
9.31 To prevent a class from being instantiated,
_____________________
A. don't use any modifiers on
the constructor.
B. use the public modifier on
the constructor.
C. use the private modifier on
the constructor.
[Link] 18/33
11/21/24, 2:04 AM Introduction to Java Programming
D. use the static modifier on
the constructor.
Your answer A is incorrect
The correct answer is C
9.32 Analyze the following code:
public class Test {
public static void main(String args[])
{
NClass nc = new NClass();
nc.t = nc.t++;
}
}
class NClass {
int t;
private NClass() {
}
}
A. The program has a compile
error because the NClass class
has a private constructor.
B. The program does not compile
because the parameter list of
the main method is wrong.
C. The program compiles, but has
a runtime error because t has
no initial value.
D. The program compiles and runs
fine.
Your answer is correct
Explanation: You cannot use the private
constructor to create an object.
[Link] 19/33
11/21/24, 2:04 AM Introduction to Java Programming
9.33 Analyze the following code:
public class Test {
private int t;
public static void main(String[] args)
{
int x;
[Link](t);
}
}
A. The variable t is not
initialized and therefore
causes errors.
B. The variable t is private and
therefore cannot be accessed
in the main method.
C. t is non-static and it cannot
be referenced in a static
context in the main method.
D. The variable x is not
initialized and therefore
causes errors.
E. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is C
9.34 Analyze the following code and choose the
best answer:
public class Foo {
private int x;
public static void main(String[] args)
{
Foo foo = new Foo();
[Link](foo.x);
[Link] 20/33
11/21/24, 2:04 AM Introduction to Java Programming
}
}
A. Since x is private, it cannot
be accessed from an object
foo.
B. Since x is defined in the
class Foo, it can be accessed
by any method inside the class
without using an object. You
can write the code to access x
without creating an object
such as foo in this code.
C. Since x is an instance
variable, it cannot be
directly used inside a main
method. However, it can be
accessed through an object
such as foo in this code.
D. You cannot create a self-
referenced object; that is,
foo is created inside the
class Foo.
Your answer A is incorrect
The correct answer is C
Explanation: (A) is incorrect, since x can be
accessed by an object of Foo inside the Foo
class. (B) is incorrect because x is non-static, it
cannot be accessed in the main method without
creating an object. (D) is incorrect, since it is
permissible to create an instance of the class
within the class. The best choice is (C).
Section 9.9 Data Field Encapsulation
9.35 Which of the following statements are true?
[Link] 21/33
11/21/24, 2:04 AM Introduction to Java Programming
A. Use the private modifier to
encapsulate data fields.
B. Encapsulating data fields
makes the program easy to
maintain.
C. Encapsulating data fields
makes the program short.
D. Encapsulating data fields
helps prevent programming
errors.
Your answer A is incorrect
The correct answer is ABD
9.36 Suppose you wish to provide an accessor
method for a boolean property finished, what
should the signature of this method?
A. public void getFinished()
B. public boolean getFinished()
C. public boolean isFinished()
D. public void isFinished()
Your answer A is incorrect
The correct answer is C
9.37 Which is the advantage of encapsulation?
A. Only public methods are
needed.
B. Making the class final causes
no consequential changes to
other code.
C. It enables changes to the
implementation without
changing a class's contract
[Link] 22/33
11/21/24, 2:04 AM Introduction to Java Programming
and causes no consequential
changes to other code.
D. It enables changes to a
class's contract without
changing the implementation
and causes no consequential
changes to other code.
Your answer A is incorrect
The correct answer is C
Section 9.10 Passing Objects to Methods
9.38 When invoking a method with an object
argument, ___________ is passed.
A. the contents of the object
B. a copy of the object
C. the reference of the object
D. the object is copied, then
the reference of the copied
object
Your answer A is incorrect
The correct answer is C
9.39 What is the value of [Link]
displayed?
public class Test {
public static void main(String[] args)
{
Count myCount = new Count();
int times = 0;
for (int i=0; i<100; i++)
increment(myCount, times);
[Link](
[Link] 23/33
11/21/24, 2:04 AM Introduction to Java Programming
"[Link] = " +
[Link]);
[Link]("times = "+
times);
}
public static void increment(Count c,
int times) {
[Link]++;
times++;
}
}
class Count {
int count;
Count(int c) {
count = c;
}
Count() {
count = 1;
}
}
A. 101
B. 100
C. 99
D. 98
Your answer is correct
9.40 What is the value of times displayed?
public class Test {
public static void main(String[] args)
{
Count myCount = new Count();
int times = 0;
for (int i=0; i<100; i++)
increment(myCount, times);
[Link] 24/33
11/21/24, 2:04 AM Introduction to Java Programming
[Link](
"[Link] = " +
[Link]);
[Link]("times = "+
times);
}
public static void increment(Count c,
int times) {
[Link]++;
times++;
}
}
class Count {
int count;
Count(int c) {
count = c;
}
Count() {
count = 1;
}
}
A. 101
B. 100
C. 99
D. 98
E. 0
Your answer A is incorrect
The correct answer is E
9.41 What is the output of the following
program?
import [Link];
public class Test {
[Link] 25/33
11/21/24, 2:04 AM Introduction to Java Programming
public static void main(String[] args)
{
Date date = new Date(1234567);
m1(date);
[Link]([Link]() + "
");
m2(date);
[Link]([Link]());
}
public static void m1(Date date) {
date = new Date(7654321);
}
public static void m2(Date date) {
[Link](7654321);
}
}
A. 1234567 1234567
B. 1234567 7654321
C. 7654321 1234567
D. 7654321 7654321
Your answer A is incorrect
The correct answer is B
Section 9.11 Array of Objects
9.42 Given the declaration Circle[] x = new
Circle[10], which of the following statement is
most accurate?
A. x contains an array of ten
int values.
B. x contains an array of ten
objects of the Circle type.
C. x contains a reference to an
array and each element in the
array can hold a reference to
a Circle object.
[Link] 26/33
11/21/24, 2:04 AM Introduction to Java Programming
D. x contains a reference to an
array and each element in the
array can hold a Circle
object.
Your answer A is incorrect
The correct answer is C
9.43 Assume [Link][] dates = new
[Link][10], which of the following
statements are true?
A. dates is null.
B. dates[0] is null.
C. dates = new [Link][5]
is fine, which assigns a new
array to dates.
D. dates = new Date() is fine,
which creates a new Date
object and assigns to dates.
Your answer A is incorrect
The correct answer is BC
Section 9.12 Immutable Objects and Classes
9.44 Which of the following statements are true
about an immutable object?
A. The contents of an immutable
object cannot be modified.
B. All properties of an immutable
object must be private.
C. All properties of an immutable
object must be of primitive
types.
[Link] 27/33
11/21/24, 2:04 AM Introduction to Java Programming
D. A readable object type
property in an immutable
object must also be immutable.
E. An immutable object contains
no mutator methods.
Your answer A is incorrect
The correct answer is ABDE
Section 9.13 Scope of Variables
9.45 What is the output for the first statement in
the main method?
public class Foo {
static int i = 0;
static int j = 0;
public static void main(String[] args)
{
int i = 2;
int k = 3;
{
int j = 3;
[Link]("i + j is " + i
+ j);
}
k = i + j;
[Link]("k is " + k);
[Link]("j is " + j);
}
}
A. i + j is 5
B. i + j is 6
C. i + j is 22
D. i + j is 23
Your answer A is incorrect
The correct answer is D
[Link] 28/33
11/21/24, 2:04 AM Introduction to Java Programming
Explanation: The first + operator in the
expression 'i + j is ' + i + j is evaluated.
9.46 What is the output for the second statement
in the main method?
public class Foo {
static int i = 0;
static int j = 0;
public static void main(String[] args)
{
int i = 2;
int k = 3;
{
int j = 3;
[Link]("i + j is " + i
+ j);
}
k = i + j;
[Link]("k is " + k);
[Link]("j is " + j);
}
}
A. k is 0
B. k is 1
C. k is 2
D. k is 3
Your answer A is incorrect
The correct answer is C
Explanation: When computing k = i + j, i is 2
and j is 0.
9.47 What is the output for the third statement in
the main method?
public class Foo {
[Link] 29/33
11/21/24, 2:04 AM Introduction to Java Programming
static int i = 0;
static int j = 0;
public static void main(String[] args)
{
int i = 2;
int k = 3;
{
int j = 3;
[Link]("i + j is " + i
+ j);
}
k = i + j;
[Link]("k is " + k);
[Link]("j is " + j);
}
}
A. j is 0
B. j is 1
C. j is 2
D. j is 3
Your answer is correct
9.48 You can declare two variables with the
same name in __________.
A. a method, one as a formal
parameter and the other as a
local variable
B. a block
C. two nested blocks in a method
(two nested blocks means one
being inside the other)
D. different methods in a class
Your answer A is incorrect
The correct answer is D
[Link] 30/33
11/21/24, 2:04 AM Introduction to Java Programming
Section 9.14 The this Keyword
9.49 Analyze the following code:
class Circle {
private double radius;
public Circle(double radius) {
radius = radius;
}
}
A. The program has a compile
error because it does not have
a main method.
B. The program will compile, but
you cannot create an object of
Circle with a specified
radius. The object will always
have radius 0.
C. The program has a compile
error because you cannot
assign radius to radius.
D. The program does not compile
because Circle does not have a
default constructor.
Your answer A is incorrect
The correct answer is B
Explanation: You have replaced radius = radius
by [Link] = radius
9.50 Analyze the following code:
class Test {
private double i;
public Test(double i) {
this.t();
this.i = i;
[Link] 31/33
11/21/24, 2:04 AM Introduction to Java Programming
}
public Test() {
[Link]("Default
constructor");
this(1);
}
public void t() {
[Link]("Invoking t");
}
}
A. this.t() may be replaced by
t().
B. this.i may be replaced by i.
C. this(1) must be called before
[Link]("Default
constructor").
D. this(1) must be replaced by
this(1.0).
Your answer A is incorrect
The correct answer is AC
9.51 Which of the following can be placed in the
blank line in the following code?
public class Test {
private int id;
public void m1() {
_____.id = 45;
}
}
A. this
B. Test
[Link] 32/33
11/21/24, 2:04 AM Introduction to Java Programming
Your answer is correct
[Link] 33/33
11/21/24, 2:08 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 10 Object-Oriented Thinking
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 10.4 Class Relationships
10.1 ___________ is attached to the class of the
composing class to denote the aggregation
relationship with the composed object.
A. An empty diamond
B. A solid diamond
C. An empty oval
D. A solid oval
Your answer is correct
10.2 An aggregation relationship is usually represented
as __________ in ___________.
[Link] 1/19
11/21/24, 2:08 AM Introduction to Java Programming
A. a data field/the aggregating class
B. a data field/the aggregated class
C. a method/the aggregating class
D. a method/the aggregated class
Your answer is correct
Section 10.7 Processing Primitive Data Type Values
as Objects
10.3 Which of the following statements will convert a
string s into i of int type?
A. i = [Link](s);
B. i = (new Integer(s)).intValue();
C. i = [Link](s).intValue();
D. i = [Link](s);
E. i = (int)([Link](s));
Your answer A is incorrect
The correct answer is ABCDE
Explanation: All fine. d performs an auto conversion
from an Integer object to int.
10.4 Which of the following statements will convert a
string s into a double value d?
A. d = [Link](s);
B. d = (new Double(s)).doubleValue();
C. d =
[Link](s).doubleValue();
D. All of the above.
Your answer A is incorrect
The correct answer is D
Explanation: All are fine. a is preferred because it
does not have to create an object.
10.5 Which of the following statements convert a
double value d into a string s?
A. s = (new Double(d)).toString();
[Link] 2/19
11/21/24, 2:08 AM Introduction to Java Programming
B. s = d;
C. s = new Double(d).stringOf();
D. s = [Link](d);
E. s = d + "";
Your answer A is incorrect
The correct answer is AE
10.6 Which of the following statements are correct?
A. [Link]("12", 2);
B. [Link](100);
C. [Link]("100");
D. [Link](100, 16);
E. [Link]("345", 8);
Your answer A is incorrect
The correct answer is CE
Explanation: A is incorrect because 12 is not a binary
number. (B) and (D) are incorrect because the first
argument in the parseInt method must be a string.
10.7 What is the output of [Link]("10", 2)?
A. 1;
B. 2;
C. 10;
D. Invalid statement;
Your answer A is incorrect
The correct answer is B
Explanation: Based on 2, 10 is 2 in decimal.
Section 10.8 Automatic Conversion Between
Primitive Types and Wrapper Class Types
10.8 In JDK 1.5, you may directly assign a primitive
data type value to a wrapper object. This is called
______________.
[Link] 3/19
11/21/24, 2:08 AM Introduction to Java Programming
A. auto boxing
B. auto unboxing
C. auto conversion
D. auto casting
Your answer is correct
10.9 In JDK 1.5, analyze the following code.
Line 1: Integer[] intArray = {1, 2, 3};
Line 2: int i = intArray[0] + intArray[1];
Line 3: int j = i + intArray[2];
Line 4: double d = intArray[0];
A. It is OK to assign 1, 2, 3 to an
array of Integer objects in JDK
1.5.
B. It is OK to automatically convert
an Integer object to an int value
in Line 2.
C. It is OK to mix an int value with
an Integer object in an expression
in Line 3.
D. Line 4 is OK. An int value from
intArray[0] object is assigned to a
double variable d.
Your answer A is incorrect
The correct answer is ABCD
Section 10.9 The BigInteger and BigDecimal Classes
10.10 To create an instance of BigInteger for 454, use
A. BigInteger(454);
B. new BigInteger(454);
C. BigInteger("454");
D. new BigInteger("454");
Your answer A is incorrect
The correct answer is D
[Link] 4/19
11/21/24, 2:08 AM Introduction to Java Programming
10.11 To create an instance of BigDecimal for 454.45,
use
A. BigDecimal(454.45);
B. new BigDecimal(454.45);
C. BigDecimal("454.45");
D. new BigDecimal("454.45");
Your answer A is incorrect
The correct answer is BD
10.12 BigInteger and BigDecimal are immutable
A. true
B. false
Your answer is correct
10.13 To add BigInteger b1 to b2, you write
_________.
A. [Link](b2);
B. [Link](b1);
C. b2 = [Link](b2);
D. b2 = [Link](b1);
E. b1 = [Link](b1);
Your answer A is incorrect
The correct answer is CD
10.14 What is the output of the following code?
public class Test {
public static void main(String[] args) {
[Link] x = new
[Link]("3");
[Link] y = new
[Link]("7");
[Link](y);
[Link](x);
}
}
[Link] 5/19
11/21/24, 2:08 AM Introduction to Java Programming
A. 3
B. 4
C. 10
D. 11
Your answer is correct
10.15 To divide BigDecimal b1 by b2 and assign the
result to b1, you write _________.
A. [Link](b2);
B. [Link](b1);
C. b1 = [Link](b2);
D. b1 = [Link](b1);
E. b2 = [Link](b1);
Your answer A is incorrect
The correct answer is C
10.16 Which of the following classes are immutable?
A. Integer
B. Double
C. BigInteger
D. BigDecimal
E. String
Your answer A is incorrect
The correct answer is ABCDE
10.17 Which of the following statements are correct?
A. new [Link]("343");
B. new
[Link]("343.445");
C. new [Link](343);
D. new [Link](343.445);
Your answer A is incorrect
The correct answer is ABD
[Link] 6/19
11/21/24, 2:08 AM Introduction to Java Programming
Section 10.10 The String Class
10.18 Which of the following statements is preferred
to create a string "Welcome to Java"?
A. String s = "Welcome to Java";
B. String s = new String("Welcome to
Java");
C. String s; s = "Welcome to Java";
D. String s; s = new String("Welcome
to Java");
Your answer is correct
Explanation: (a) is better than (b) because the string
created in (a) is interned. Since strings are immutable
and are ubiquitous in programming, to improve
efficiency and save memory, the JVM uses a unique
instance for string literals with the same character
sequence. Such an instance is called interned. The
JVM (a) is simpler than (c).
10.19 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = "Welcome to Java!";
String s2 = s1;
if (s1 == s2)
[Link]("s1 and s2 reference
to the same String object");
else
[Link]("s1 and s2 reference
to different String objects");
}
}
A. s1 and s2 reference to the same
String object
B. s1 and s2 reference to different
String objects
Your answer is correct
[Link] 7/19
11/21/24, 2:08 AM Introduction to Java Programming
10.20 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = "Welcome to Java!";
String s2 = "Welcome to Java!";
if (s1 == s2)
[Link]("s1 and s2 reference
to the same String object");
else
[Link]("s1 and s2 reference
to different String objects");
}
}
A. s1 and s2 reference to the same
String object
B. s1 and s2 reference to different
String objects
Your answer is correct
Explanation: Since strings are immutable and are
ubiquitous in programming, to improve efficiency
and save memory, the JVM uses a unique instance
for string literals with the same character sequence.
Such an instance is called interned.
10.21 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Welcome to
Java!");
String s2 = new String("Welcome to
Java!");
if (s1 == s2)
[Link]("s1 and s2 reference
to the same String object");
else
[Link]("s1 and s2 reference
to different String objects");
}
}
[Link] 8/19
11/21/24, 2:08 AM Introduction to Java Programming
A. s1 and s2 reference to the same
String object
B. s1 and s2 reference to different
String objects
Your answer A is incorrect
The correct answer is B
10.22 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Welcome to
Java!");
String s2 = new String("Welcome to
Java!");
if ([Link](s2))
[Link]("s1 and s2 have the
same contents");
else
[Link]("s1 and s2 have
different contents");
}
}
A. s1 and s2 have the same contents
B. s1 and s2 have different contents
Your answer is correct
10.23 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Welcome to
Java!");
String s2 = [Link]();
if (s1 == s2)
[Link]("s1 and s2 reference
to the same String object");
else if ([Link](s2))
[Link]("s1 and s2 have the
same contents");
[Link] 9/19
11/21/24, 2:08 AM Introduction to Java Programming
else
[Link]("s1 and s2 have
different contents");
}
}
A. s1 and s2 reference to the same
String object
B. s1 and s2 have the same contents
C. s1 and s2 have different contents
Your answer A is incorrect
The correct answer is C
10.24 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Welcome to
Java");
String s2 = s1;
s1 += "and Welcome to HTML";
if (s1 == s2)
[Link]("s1 and s2 reference
to the same String object");
else
[Link]("s1 and s2 reference
to different String objects");
}
}
A. s1 and s2 reference to the same
String object
B. s1 and s2 reference to different
String objects
Your answer A is incorrect
The correct answer is B
10.25 Suppose s1 and s2 are two strings. Which of the
following statements or expressions are incorrect?
[Link] 10/19
11/21/24, 2:08 AM Introduction to Java Programming
A. String s = new String("new
string");
B. String s3 = s1 + s2
C. s1 >= s2
D. int i = [Link]
E. [Link](0) = '5'
Your answer A is incorrect
The correct answer is CDE
10.26 What is the output of the following code?
String s = "University";
[Link]("i", "ABC");
[Link](s);
A. UnABCversity
B. UnABCversABCty
C. UniversABCty
D. University
Your answer A is incorrect
The correct answer is D
Explanation: No method in the String class can
change the content of the string. String is an
immutable class.
10.27 Analyze the following code.
class Test {
public static void main(String[] args) {
String s;
[Link]("s is " + s);
}
}
A. The program has a compile error
because s is not initialized, but
it is referenced in the println
statement.
B. The program has a runtime error
because s is not initialized, but
[Link] 11/19
11/21/24, 2:08 AM Introduction to Java Programming
it is referenced in the println
statement.
C. The program has a runtime error
because s is null in the println
statement.
D. The program compiles and runs
fine.
Your answer is correct
10.28 Which of the following is the correct statement
to return a string from an array a of characters?
A. toString(a)
B. new String(a)
C. convertToString(a)
D. [Link](a)
Your answer A is incorrect
The correct answer is B
10.29 Assume s is " abc ", the method __________
returns a new string "abc".
A. [Link](s)
B. trim(s)
C. [Link](s)
D. [Link]()
Your answer A is incorrect
The correct answer is D
10.30 Assume s is "ABCABC", the method
__________ returns a new string "aBCaBC".
A. [Link](s)
B. [Link]()
C. [Link]('A', 'a')
D. [Link]('a', 'A')
E. [Link]("ABCABC", "aBCaBC")
[Link] 12/19
11/21/24, 2:08 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is CE
10.31 Assume s is "ABCABC", the method
__________ returns an array of characters.
A. toChars(s)
B. [Link]()
C. [Link]()
D. [Link]()
E. [Link]()
Your answer A is incorrect
The correct answer is B
10.32 __________ returns a string.
A. [Link](123)
B. [Link](12.53)
C. [Link](false)
D. [Link](new char[]{'a',
'b', 'c'})
Your answer A is incorrect
The correct answer is ABCD
10.33 The following program displays __________.
public class Test {
public static void main(String[] args) {
String s = "Java";
StringBuilder builder = new
StringBuilder(s);
change(s);
[Link](s);
}
private static void change(String s) {
s = s + " and HTML";
[Link] 13/19
11/21/24, 2:08 AM Introduction to Java Programming
}
}
A. Java
B. Java and HTML
C. and HTML
D. nothing is displayed
Your answer is correct
Explanation: Inside the method, the statement s = s +
' and HTML' creates a new String object s, which is
different from the original String object passed to the
change(s) method. The original String object has not
been changed. Therefore, the output from the original
string is Java.
10.34 What is displayed by the following statement?
[Link]("Java is neat".replaceAll("is", "AAA"
A. JavaAAAneat
B. JavaAAA neat
C. Java AAA neat
D. Java AAAneat
Your answer A is incorrect
The correct answer is C
10.35 What is displayed by the following code?
public static void main(String[] args) {
String[] tokens = "Welcome to
Java".split("o");
for (int i = 0; i < [Link]; i++) {
[Link](tokens[i] + " ");
}
}
A. Welcome to Java
B. Welc me to Java
C. Welc me t Java
D. Welcome t Java
[Link] 14/19
11/21/24, 2:08 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
10.36 What is displayed by the following code?
[Link]("Hi, ABC, good".matches("ABC ") + " ");
[Link]("Hi, ABC, good".matches(".*ABC.*"));
A. false false
B. true false
C. true true
D. false true
Your answer A is incorrect
The correct answer is D
10.37 What is displayed by the following code?
[Link]("A,B;C".replaceAll(",;", "#") + " ");
[Link]("A,B;C".replaceAll("
[,;]", "#"));
A. A B C A#B#C
B. A#B#C A#B#C
C. A,B;C A#B#C
D. A B C A B C
Your answer A is incorrect
The correct answer is C
10.38 What is displayed by the following code?
String[] tokens = "A,B;C;D".split("[,;]");
for (int i = 0; i < [Link]; i++)
[Link](tokens[i] + " ");
A. A,B;C;D
B. A B C D
C. A B C;D
D. A B;C;D
[Link] 15/19
11/21/24, 2:08 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
Section 10.11 The StringBuilder/StringBuffer Class
10.39 Analyze the following code.
class Test {
public static void main(String[] args) {
StringBuilder strBuilder = new
StringBuilder(4);
[Link]("ABCDE");
[Link]("What's
[Link](5)? " +
[Link](5));
}
}
A. The program has a compile error
because you cannot specify initial
capacity in the StringBuilder
constructor.
B. The program has a runtime error
because because the builder's
capacity is 4, but five characters
"ABCDE" are appended into the
builder.
C. The program has a runtime error
because the length of the string in
the builder is 5 after "ABCDE" is
appended into the builder.
Therefore, [Link](5) is
out of range.
D. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is C
Explanation: The charAt method returns the
character at a specific index in the string builder. The
first character of a string builder is at index 0, the
next at index 1, and so on. The index argument must
[Link] 16/19
11/21/24, 2:08 AM Introduction to Java Programming
be greater than or equal to 0, and less than the length
of the string builder.
10.40 Which of the following is true?
A. You can add characters into a
string builder.
B. You can delete characters from a
string builder.
C. You can reverse the characters in
a string buffer.
D. The capacity of a string buffer
can be automatically adjusted.
Your answer A is incorrect
The correct answer is ABCD
10.41 _________ returns the last character in a
StringBuilder variable named strBuilder?
A.
[Link]([Link]()
- 1)
B.
[Link]([Link]()
- 1)
C.
[Link]([Link]()
- 1)
D.
[Link]([Link]()
- 1)
Your answer is correct
10.42 Assume StringBuilder strBuilder is
"ABCDEFG", after invoking _________, strBuilder
contains "AEFG".
A. [Link](0, 3)
B. [Link](1, 3)
[Link] 17/19
11/21/24, 2:08 AM Introduction to Java Programming
C. [Link](1, 4)
D. [Link](2, 4)
Your answer A is incorrect
The correct answer is C
10.43 Assume StringBuilder strBuilder is
"ABCDEFG", after invoking _________, strBuilder
contains "ABCRRRRDEFG".
A. [Link](1, "RRRR")
B. [Link](2, "RRRR")
C. [Link](3, "RRRR")
D. [Link](4, "RRRR")
Your answer A is incorrect
The correct answer is C
10.44 Assume StringBuilder strBuilder is
"ABCCEFC", after invoking _________, strBuilder
contains "ABTTEFT".
A. [Link]('C', 'T')
B. [Link]("C", "T")
C. [Link]("CC", "TT")
D. [Link]('C', "TT")
E. [Link](2, 7, "TTEFT")
Your answer A is incorrect
The correct answer is E
10.45 The StringBuilder methods _____________ not
only change the contents of a string builder, but also
returns a reference to the string builder.
A. delete
B. append
C. insert
D. reverse
E. replace
[Link] 18/19
11/21/24, 2:08 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is ABCDE
10.46 The following program displays __________.
public class Test {
public static void main(String[] args) {
String s = "Java";
StringBuilder builder = new
StringBuilder(s);
change(builder);
[Link](builder);
}
private static void change(StringBuilder
builder) {
[Link](" and HTML");
}
}
A. Java
B. Java and HTML
C. and HTML
D. nothing is displayed
Your answer A is incorrect
The correct answer is B
Explanation: Inside the method, the content of the
StringBuilder object is changed to Java and HTML.
Therefore, the output from builder is Java and
HTML.
[Link] 19/19
11/21/24, 2:13 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 11 Inheritance and
Polymorphism
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 11.2 Superclasses and Subclasses
11.1 Object-oriented programming allows you to
derive new classes from existing classes. This is
called ____________.
A. encapsulation
B. inheritance
C. abstraction
D. generalization
Your answer A is incorrect
The correct answer is B
[Link] 1/38
11/21/24, 2:13 AM Introduction to Java Programming
11.2 Which of the following statements are true?
A. A subclass is a subset of a
superclass.
B. A subclass is usually extended to
contain more functions and more
detailed information than its
superclass.
C. "class A extends B" means A is a
subclass of B.
D. "class A extends B" means B is a
subclass of A.
Your answer A is incorrect
The correct answer is BC
Section 11.3 Using the super Keyword Section 11.3.1
Calling Superclass Constructors
11.3 Suppose you create a class Square to be a
subclass of GeometricObject. Analyze the following
code:
class Square extends GeometricObject {
double length;
Square(double length) {
GeometricObject(length);
}
}
A. The program compiles fine, but you
cannot create an instance of Square
because the constructor does not
specify the length of the Square.
B. The program has a compile error
because you attempted to invoke the
GeometricObject class's constructor
illegally.
C. The program compiles fine, but it
has a runtime error because of
[Link] 2/38
11/21/24, 2:13 AM Introduction to Java Programming
invoking the Square class's
constructor illegally.
Your answer A is incorrect
The correct answer is B
Explanation: You have to use super() or
super(withapproriatearguments) to invoke a super
class constructor explicitly.
11.4 Analyze the following code:
public class A extends B {
}
class B {
public B(String s) {
}
}
A. The program has a compile error
because A does not have a default
constructor.
B. The program has a compile error
because the default constructor of
A invokes the default constructor
of B, but B does not have a default
constructor.
C. The program would compile fine if
you add the following constructor
into A: A(String s) { }
D. The program would compile fine if
you add the following constructor
into A: A(String s) { super(s); }
Your answer A is incorrect
The correct answer is BD
11.5 Analyze the following code:
public class Test extends A {
public static void main(String[] args) {
Test t = new Test();
[Link] 3/38
11/21/24, 2:13 AM Introduction to Java Programming
[Link]();
}
}
class A {
String s;
A(String s) {
this.s = s;
}
public void print() {
[Link](s);
}
}
A. The program does not compile
because Test does not have a
default constructor Test().
B. The program has an implicit
default constructor Test(), but it
cannot be compiled, because its
super class does not have a default
constructor. The program would
compile if the constructor in the
class A were removed.
C. The program would compile if a
default constructor A(){ } is added
to class A explicitly.
D. The program compiles, but it has a
runtime error due to the conflict
on the method name print.
Your answer A is incorrect
The correct answer is BC
Explanation: See the last Note in the section, 'Using
the super keyword.'
Section 11.3.2 Constructor Chaining
11.6 What is the output of running class C?
class A {
public A() {
[Link] 4/38
11/21/24, 2:13 AM Introduction to Java Programming
[Link](
"The default constructor of A is
invoked");
}
}
class B extends A {
public B() {
[Link](
"The default constructor of B is
invoked");
}
}
public class C {
public static void main(String[] args) {
B b = new B();
}
}
A. Nothing displayed
B. "The default constructor of B is
invoked"
C. "The default constructor of A is
invoked" followed by "The default
constructor of B is invoked"
D. "The default constructor of B is
invoked" followed by "The default
constructor of A is invoked"
E. "The default constructor of A is
invoked"
Your answer A is incorrect
The correct answer is C
Explanation: Superclass's constructor is called before
executing the statements in the subclass constructor.
11.7 Which of the following is incorrect?
A. A constructor may be static.
B. A constructor may be private.
C. A constructor may invoke a static
method.
[Link] 5/38
11/21/24, 2:13 AM Introduction to Java Programming
D. A constructor may invoke an
overloaded constructor.
E. A constructor invokes its
superclass no-arg constructor by
default if a constructor does not
invoke an overloaded constructor or
its superclass's constructor.
Your answer is correct
Explanation: A constructor cannot be static, because
you use a constructor to create a specific instance. A
constructor may be private. In this case, the use
cannot create an instance using this constructor. For
example, the constructor in the Math class is private.
A constructor may invoke a static method just like
any method can invoke a static method. A constructor
can invoke an overloaded constructor using the this
keyword. So, the correct answer is A.
Section 11.3.3 Calling Superclass Methods
11.8 Which of the statements regarding the super
keyword is incorrect?
A. You can use super to invoke a
super class constructor.
B. You can use super to invoke a
super class method.
C. You can use [Link].p to
invoke a method in superclass's
parent class.
D. You cannot invoke a method in
superclass's parent class.
Your answer A is incorrect
The correct answer is C
Explanation: Using [Link] is not allowed in
Java. So, the answer to this question is C.
Section 11.4 Overriding Methods
[Link] 6/38
11/21/24, 2:13 AM Introduction to Java Programming
11.9 Analyze the following code:
public class Test {
public static void main(String[] args) {
B b = new B();
b.m(5);
[Link]("i is " + b.i);
}
}
class A {
int i;
public void m(int i) {
this.i = i;
}
}
class B extends A {
public void m(String s) {
}
}
A. The program has a compile error,
because m is overridden with a
different signature in B.
B. The program has a compile error,
because b.m(5) cannot be invoked
since the method m(int) is hidden
in B.
C. The program has a runtime error on
b.i, because i is not accessible
from b.
D. The method m is not overridden in
B. B inherits the method m from A
and defines an overloaded method m
in B.
Your answer A is incorrect
The correct answer is D
11.10 The getValue() method is overridden in two
ways. Which one is correct?
[Link] 7/38
11/21/24, 2:13 AM Introduction to Java Programming
I:
public class Test {
public static void main(String[] args) {
A a = new A();
[Link]([Link]());
}
}
class B {
public String getValue() {
return "Any object";
}
}
class A extends B {
public Object getValue() {
return "A string";
}
}
II:
public class Test {
public static void main(String[] args) {
A a = new A();
[Link]([Link]());
}
}
class B {
public Object getValue() {
return "Any object";
}
}
class A extends B {
public String getValue() {
return "A string";
}
}
A. I
B. II
C. Both I and II
D. Neither
Your answer A is incorrect
The correct answer is B
[Link] 8/38
11/21/24, 2:13 AM Introduction to Java Programming
Section 11.5 Overriding vs. Overloading
11.11 Which of the following statements are true?
A. To override a method, the method
must be defined in the subclass
using the same signature and
compatible return type as in its
superclass.
B. Overloading a method is to provide
more than one method with the same
name but with different signatures
to distinguish them.
C. It is a compile error if two
methods differ only in return type
in the same class.
D. A private method cannot be
overridden. If a method defined in
a subclass is private in its
superclass, the two methods are
completely unrelated.
E. A static method cannot be
overridden. If a static method
defined in the superclass is
redefined in a subclass, the method
defined in the superclass is
hidden.
Your answer A is incorrect
The correct answer is ABCDE
11.12 Which of the following statements are true?
A. A method can be overloaded in the
same class.
B. A method can be overridden in the
same class.
C. If a method overloads another
method, these two methods must have
the same signature.
[Link] 9/38
11/21/24, 2:13 AM Introduction to Java Programming
D. If a method overrides another
method, these two methods must have
the same signature.
E. A method in a subclass can
overload a method in the
superclass.
Your answer A is incorrect
The correct answer is ADE
11.13 Analyze the following code:
public class Test {
public static void main(String[] args) {
new B();
}
}
class A {
int i = 7;
public A() {
[Link]("i from A is " + i);
}
public void setI(int i) {
this.i = 2 * i;
}
}
class B extends A {
public B() {
setI(20);
// [Link]("i from B is " +
i);
}
@Override
public void setI(int i) {
this.i = 3 * i;
}
}
A. The constructor of class A is not
called.
[Link] 10/38
11/21/24, 2:13 AM Introduction to Java Programming
B. The constructor of class A is
called and it displays "i from A is
7".
C. The constructor of class A is
called and it displays "i from A is
40".
D. The constructor of class A is
called and it displays "i from A is
60".
Your answer A is incorrect
The correct answer is B
Explanation: When invoking new B(), B's superclass
A's constructor is invoked first. So it displays i from
A is 7.
11.14 Analyze the following code:
public class Test {
public static void main(String[] args) {
new B();
}
}
class A {
int i = 7;
public A() {
setI(20);
[Link]("i from A is " + i);
}
public void setI(int i) {
this.i = 2 * i;
}
}
class B extends A {
public B() {
// [Link]("i from B is " +
i);
}
@Override
[Link] 11/38
11/21/24, 2:13 AM Introduction to Java Programming
public void setI(int i) {
this.i = 3 * i;
}
}
A. The constructor of class A is not
called.
B. The constructor of class A is
called and it displays "i from A is
7".
C. The constructor of class A is
called and it displays "i from A is
40".
D. The constructor of class A is
called and it displays "i from A is
60".
Your answer A is incorrect
The correct answer is D
Explanation: When invoking new B(), B's superclass
A's constructor is invoked first. It invokes setI(20).
The setI method in B is used because object created
is new B(). The setI method in B assigns 3 * 20 to i.
So it displays i from A is 60.
Section 11.6 The Object Class and Its toString()
Method
11.15 Analyze the following code:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new Object();
[Link](a1);
[Link](a2);
}
}
class A {
int x;
@Override
public String toString() {
[Link] 12/38
11/21/24, 2:13 AM Introduction to Java Programming
return "A's x is " + x;
}
}
A. The program cannot be compiled,
because [Link](a1) is
wrong and it should be replaced by
[Link]([Link]());
B. When executing
[Link](a1), the
toString() method in the Object
class is invoked.
C. When executing
[Link](a2), the
toString() method in the Object
class is invoked.
D. When executing
[Link](a1), the
toString() method in the A class is
invoked.
Your answer A is incorrect
The correct answer is CD
Explanation: Since a1 is an instance of A, the
toString() method in the A class is invoked at
runtime.
Section 11.7 Polymorphism
11.16 Given the following code, find the compile
error.
public class Test {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Student x) {
[Link]([Link]());
}
}
[Link] 13/38
11/21/24, 2:13 AM Introduction to Java Programming
class GraduateStudent extends Student {
}
class Student extends Person {
@Override
public String toString() {
return "Student";
}
}
class Person extends Object {
@Override
public String toString() {
return "Person";
}
}
A. m(new GraduateStudent()) causes an
error
B. m(new Student()) causes an error
C. m(new Person()) causes an error
D. m(new Object()) causes an error
Your answer A is incorrect
The correct answer is CD
Explanation: You cannot pass a supertype variable to
a subtype without explicit casting.
Section 11.8 Dynamic Binding
11.17 What is the output of the following code?
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
@Override
public String getInfo() {
return "Student";
}
}
[Link] 14/38
11/21/24, 2:13 AM Introduction to Java Programming
class Person {
public String getInfo() {
return "Person";
}
public void printPerson() {
[Link](getInfo());
}
}
A. Person Person
B. Person Student
C. Student Student
D. Student Person
Your answer A is incorrect
The correct answer is B
11.18 What is the output of the following code?
public class Test {
public static void main(String[] args) {
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person {
private String getInfo() {
return "Student";
}
}
class Person {
private String getInfo() {
return "Person";
}
public void printPerson() {
[Link](getInfo());
}
}
A. Person Person
B. Person Student
[Link] 15/38
11/21/24, 2:13 AM Introduction to Java Programming
C. Student Student
D. Student Person
Your answer is correct
Explanation: Note that the getInfo method is private
in Person. It is not known to the outside of the class.
This is the method invoked from the printPerson()
method.
11.19 Which of the following statements is false?
A. You can always pass an instance of
a subclass to a parameter of its
superclass type. This feature is
known as polymorphism.
B. The compiler finds a matching
method according to parameter type,
number of parameters, and order of
the parameters at compile time.
C. A method may be implemented in
several subclasses. The Java
Virtual Machine dynamically binds
the implementation of the method at
runtime.
D. Dynamic binding can apply to
static methods.
E. Dynamic binding can apply to
instance methods.
Your answer A is incorrect
The correct answer is D
Explanation: Dynamic binding is applied to instance
methods, not static methods. Static methods are
bound in the compile time.
Section 11.9 Casting Objects and the instanceof
Operator
11.20 Which of the following are Java keywords?
[Link] 16/38
11/21/24, 2:13 AM Introduction to Java Programming
A. instanceOf
B. instanceof
C. cast
D. casting
Your answer A is incorrect
The correct answer is B
Explanation: A simple rule: the keywords are all in
lowercase.
11.21 Assume Cylinder is a subtype of Circle. Analyze
the following code:
Cylinder cy = new Cylinder(1, 1);
Circle c = cy;
A. The code has a compile error.
B. The code has a runtime error.
C. The code is fine.
Your answer A is incorrect
The correct answer is C
Explanation: You can assign a variable of a subtype
to a supertype.
11.22 Assume Cylinder is a subtype of Circle. Analyze
the following code:
Circle c = new Circle (5);
Cylinder c = cy;
A. The code has a compile error.
B. The code has a runtime error.
C. The code is fine.
Your answer is correct
Explanation: You cannot assign a variable of a
supertype to a subtype without explicit casting.
[Link] 17/38
11/21/24, 2:13 AM Introduction to Java Programming
11.23 Given the following classes and their objects:
class C1 {};
class C2 extends C1 {};
class C3 extends C1 {};
C2 c2 = new C2();
C3 c3 = new C3();
Analyze the following statement:
c2 = (C2)((C1)c3);
A. c3 is cast into c2 successfully.
B. You will get a runtime error
because you cannot cast objects
from sibling classes.
C. You will get a runtime error
because the Java runtime system
cannot perform multiple casting in
nested form.
D. The statement is correct.
Your answer A is incorrect
The correct answer is B
11.24 Given the following code, which of the
following expressions evaluates to false?
class C1 {}
class C2 extends C1 { }
class C3 extends C2 { }
class C4 extends C1 {}
C1 c1 = new C1();
C2 c2 = new C2();
C3 c3 = new C3();
C4 c4 = new C4();
A. c1 instanceof C1
B. c2 instanceof C1
C. c3 instanceof C1
D. c4 instanceof C2
[Link] 18/38
11/21/24, 2:13 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is D
11.25 Analyze the following code:
public class Test {
public static void main(String[] args) {
String s = new String("Welcome to Java");
Object o = s;
String d = (String)o;
}
}
A. When assigning s to o in Object o
= s, a new object is created.
B. When casting o to s in String d =
(String)o, a new object is created.
C. When casting o to s in String d =
(String)o, the contents of o is
changed.
D. s, o, and d reference the same
String object.
Your answer A is incorrect
The correct answer is D
Explanation: Casting object reference variable does
not affect the contents of the object.
11.26 You can assign _________ to a variable of
Object[] type.
A. new char[100]
B. new int[100]
C. new double[100]
D. new String[100]
E. new [Link][100]
Your answer A is incorrect
The correct answer is DE
[Link] 19/38
11/21/24, 2:13 AM Introduction to Java Programming
Explanation: Primitive data type array is not
compatible with Object[].
Section 11.10 The Object?s equals() Method
11.27 The equals method is defined in the Object
class. Which of the following is correct to override it
in the String class?
A. public boolean equals(String
other)
B. public boolean equals(Object
other)
C. public static boolean
equals(String other)
D. public static boolean
equals(Object other)
Your answer A is incorrect
The correct answer is B
11.28 Which of the following statements are true?
A. Override the equals(Object) method
in the Object class whenever
possible.
B. Override the toString() method in
the Object class whenever possible.
C. A public default no-arg
constructor is assumed if no
constructors are defined
explicitly.
D. You should follow standard Java
programming style and naming
conventions. Choose informative
names for classes, data fields, and
methods.
Your answer A is incorrect
The correct answer is ABCD
[Link] 20/38
11/21/24, 2:13 AM Introduction to Java Programming
11.29 What is the output of the following code?
public class Test {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
[Link]((o1 == o2) + " " +
([Link](o2)));
}
}
A. false false
B. true true
C. false true
D. true false
Your answer is correct
Explanation: o1 == o2 is false, since o1 and o2 are
two different objects. [Link](o2) is false since the
equals method returns o1 == o2 in the Object class.
11.30 What is the output of the following code?
public class Test {
public static void main(String[] args) {
String s1 = new String("Java");
String s2 = new String("Java");
[Link]((s1 == s2) + " " +
([Link](s2)));
}
}
A. false false
B. true true
C. false true
D. true false
Your answer A is incorrect
The correct answer is C
Explanation: s1 == s2 is false, since s1 and s2 are
two different objects. [Link](s2) is true since the
equals method returns true if two strings have the
same content.
[Link] 21/38
11/21/24, 2:13 AM Introduction to Java Programming
11.31 Given two reference variables t1 and t2, if t1 ==
t2 is true, [Link](t2) must be ___________.
A. true
B. false
Your answer is correct
11.32 Given two reference variables t1 and t2, if
[Link](t2) is true, t1 == t2 ___________.
A. is always true
B. is always false
C. may be true or false
Your answer A is incorrect
The correct answer is C
Explanation: Two different objects may be equal with
the same contents.
11.33 Analyze the following code.
// Program 1:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
[Link]([Link](a2));
}
}
class A {
int x;
public boolean equals(Object a) {
return this.x == ((A)a).x;
}
}
// Program 2:
public class Test {
public static void main(String[] args) {
[Link] 22/38
11/21/24, 2:13 AM Introduction to Java Programming
Object a1 = new A();
Object a2 = new A();
[Link]([Link](a2));
}
}
class A {
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
A. Program 1 displays true and
Program 2 displays true
B. Program 1 displays false and
Program 2 displays true
C. Program 1 displays true and
Program 2 displays false
D. Program 1 displays false and
Program 2 displays false
Your answer A is incorrect
The correct answer is C
Explanation: In Program 1, the equals method in the
Object class is overridden. [Link](a2) invokes this
method. It returns true. In Program 2, the equals
method in the Object class is not overridden.
[Link](a2) invokes the equals method defined in
the Object class, which returns false in this case.
11.34 Analyze the following code.
// Program 1:
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
[Link]([Link](a2));
}
}
class A {
[Link] 23/38
11/21/24, 2:13 AM Introduction to Java Programming
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
// Program 2:
public class Test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
[Link]([Link](a2));
}
}
class A {
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
A. Program 1 displays true and
Program 2 displays true
B. Program 1 displays false and
Program 2 displays true
C. Program 1 displays true and
Program 2 displays false
D. Program 1 displays false and
Program 2 displays false
Your answer A is incorrect
The correct answer is B
Explanation: In Program 1, the equals method in the
Object class is invoked. In Program 2, the equals
method in the class A is invoked. There are now two
overloaded methods available in the class A. i.e.
public boolean equals(Object a) and public boolean
equals(A a). Which of the two is used by
[Link](a2) is determined at compile time.
[Link](a2) in Program 1 matches the equals
method defined in Object and [Link](a2) in
[Link] 24/38
11/21/24, 2:13 AM Introduction to Java Programming
Program 2 matches the equals method defined in the
class A.
11.35 Analyze the following code.
// Program 1
public class Test {
public static void main(String[] args) {
Object a1 = new A();
Object a2 = new A();
[Link](((A)a1).equals((A)a2));
}
}
class A {
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
// Program 2
public class Test {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
[Link]([Link](a2));
}
}
class A {
int x;
public boolean equals(A a) {
return this.x == a.x;
}
}
A. Program 1 displays true and
Program 2 displays true
B. Program 1 displays false and
Program 2 displays true
C. Program 1 displays true and
Program 2 displays false
[Link] 25/38
11/21/24, 2:13 AM Introduction to Java Programming
D. Program 1 displays false and
Program 2 displays false
Your answer is correct
Explanation: In Program 1, ((A)a1).equals((A)a2)
matches the equals(A a) method in the class A.
Section 11.11 The ArrayList Class
11.36 You can create an ArrayList using _________.
A. new ArrayList[]
B. new ArrayList[100]
C. new ArrayList<>()
D. ArrayList()
Your answer A is incorrect
The correct answer is C
11.37 Invoking _________ removes all elements in an
ArrayList x.
A. [Link]()
B. [Link]()
C. [Link]()
D. [Link]()
E. [Link]()
Your answer A is incorrect
The correct answer is E
11.38 Suppose ArrayList x contains two strings
[Beijing, Singapore]. Which of the following
methods will cause the list to become [Beijing,
Chicago, Singapore]?
A. [Link]("Chicago")
B. [Link](0, "Chicago")
C. [Link](1, "Chicago")
D. [Link](2, "Chicago")
[Link] 26/38
11/21/24, 2:13 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
11.39 Suppose ArrayList x contains two strings
[Beijing, Singapore]. Which of the following method
will cause the list to become [Beijing]?
A. [Link]("Singapore")
B. [Link](0)
C. [Link](1)
D. [Link](2)
Your answer A is incorrect
The correct answer is AC
11.40 Suppose ArrayList x contains two strings
[Beijing, Singapore]. Which of the following method
will cause runtime errors?
A. [Link](1)
B. [Link](2, "New York");
C. [Link](2)
D. [Link](2)
E. [Link]()
Your answer A is incorrect
The correct answer is BCD
Explanation: There is no element at index 2.
11.41 Invoking _________ returns the first element in
an ArrayList x.
A. [Link]()
B. [Link](0)
C. [Link](1)
D. [Link]()
Your answer A is incorrect
The correct answer is B
[Link] 27/38
11/21/24, 2:13 AM Introduction to Java Programming
11.42 Invoking _________ returns the number of the
elements in an ArrayList x.
A. [Link]()
B. [Link](0)
C. [Link](1)
D. [Link]()
Your answer A is incorrect
The correct answer is D
11.43 Analyze the following code:
ArrayList<String> list = new ArrayList<String>
();
[Link]("Beijing");
[Link]("Tokyo");
[Link]("Shanghai");
[Link](3, "Hong Kong");
A. The last line in the code causes a
runtime error because there is no
element at index 3 in the array
list.
B. The last line in the code has a
compile error because there is no
element at index 3 in the array
list.
C. If you replace the last line by
[Link](3, "Hong Kong"), the code
will compile and run fine.
D. If you replace the last line by
[Link](4, "Hong Kong"), the code
will compile and run fine.
Your answer A is incorrect
The correct answer is AC
Explanation: There is no element at index 3.
[Link] 28/38
11/21/24, 2:13 AM Introduction to Java Programming
11.44 What is the output of the following code?
ArrayList<[Link]> list = new ArrayList<[Link]
();
[Link] d = new [Link]();
[Link](d);
[Link](d);
[Link](([Link](0) == [Link](1)) + " "
+ ([Link](0)).equals([Link](1)));
A. true false
B. false true
C. true true
D. false false
Your answer A is incorrect
The correct answer is C
Explanation: [Link](0) and [Link](1) point to the
same object.
11.45 What is the output of the following code?
ArrayList<String> list = new ArrayList<String>
();
String s1 = new String("Java");
String s2 = new String("Java");
[Link](s1);
[Link](s2);
[Link](([Link](0) == [Link](1)) + " "
+ ([Link](0)).equals([Link](1)));
A. true false
B. false true
C. true true
D. false false
Your answer A is incorrect
The correct answer is B
Explanation: [Link](0) and [Link](1) point to two
different objects with the same string contents.
11.46 Suppose an ArrayList list contains {"red",
"green", "red", "green"}. What is the list after the
[Link] 29/38
11/21/24, 2:13 AM Introduction to Java Programming
following code?
[Link]("red");
A. {"red", "green", "red", "green"}
B. {"green", "red", "green"}
C. {"green", "green"}
D. {"red", "green", "green"}
Your answer A is incorrect
The correct answer is B
11.47 Suppose an ArrayList list contains {"red", "red",
"green"}. What is the list after the following code?
String element = "red";
for (int i = 0; i < [Link](); i++)
if ([Link](i).equals(element))
[Link](element);
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
Your answer A is incorrect
The correct answer is B
11.48 Suppose an ArrayList list contains {"red", "red",
"green"}. What is the list after the following code?
String element = "red";
for (int i = 0; i < [Link](); i++)
if ([Link](i).equals(element)) {
[Link](element);
i--;
}
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
[Link] 30/38
11/21/24, 2:13 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
11.49 Suppose an ArrayList list contains {"red", "red",
"green"}. What is the list after the following code?
String element = "red";
for (int i = [Link]() - 1; i >= 0; i--)
if ([Link](i).equals(element))
[Link](element);
A. {"red", "red", "green"}
B. {"red", "green"}
C. {"green"}
D. {}
Your answer A is incorrect
The correct answer is C
11.50 The output from the following code is
__________.
[Link]<String> list
= new [Link]<String>();
[Link]("New York");
[Link]<String> list1 = list;
[Link]("Atlanta");
[Link]("Dallas");
[Link](list1);
A. [New York]
B. [New York, Atlanta]
C. [New York, Atlanta, Dallas]
D. [New York, Dallas]
Your answer A is incorrect
The correct answer is C
Section 11.12 Useful Methods for Lists
[Link] 31/38
11/21/24, 2:13 AM Introduction to Java Programming
11.51 Show the output of the following code:
String[] array = {"red", "green", "blue"};
ArrayList<String> list = new ArrayList<>
([Link](array));
[Link](0, "red");
[Link](list);
A. ["red", "green", "blue", "red"]
B. ["red", "green", "blue"]
C. ["red", "red", "green", "blue"]
D. ["red", "green", "red", "blue"]
Your answer A is incorrect
The correct answer is C
11.52 Analyze the following code:
Double[] array = {1, 2, 3};
ArrayList<Double> list = new ArrayList<>
([Link](array));
[Link](list);
A. The code is correct and displays
[1, 2, 3].
B. The code is correct and displays
[1.0, 2.0, 3.0].
C. The code has a compile error
because an integer such as 1 is
automatically converted into an
Integer object, but the array
element type is Double.
D. The code has a compile error
because asList(array) requires that
the array elements are objects.
Your answer A is incorrect
The correct answer is C
11.53 Analyze the following code:
double[] array = {1, 2, 3};
[Link] 32/38
11/21/24, 2:13 AM Introduction to Java Programming
ArrayList<Double> list = new ArrayList<>
([Link](array));
[Link](list);
A. The code is correct and displays
[1, 2, 3].
B. The code is correct and displays
[1.0, 2.0, 3.0].
C. The code has a compile error
because an integer such as 1 is
automatically converted into an
Integer object, but the array
element type is Double.
D. The code has a compile error
because asList(array) requires that
the array elements are objects.
Your answer A is incorrect
The correct answer is D
11.54 Analyze the following code:
double[] c = {1, 2, 3};
[Link]([Link](c));
A. The code is correct and displays
3.
B. The code is correct and displays
3.0.
C. The code has a compile error on
[Link](c). c cannot be an
array.
D. The code has a compile error on
double[] c = {1, 2, 3}.
Your answer A is incorrect
The correct answer is C
11.55 Analyze the following code:
Integer[] c = {3, 5};
[Link] 33/38
11/21/24, 2:13 AM Introduction to Java Programming
[Link](c);
[Link]([Link](c));
A. The code is correct and displays
[3, 5].
B. The code is correct and displays
[5, 3].
C. The code has a compile error on
[Link](c). c cannot be
an array.
D. The code has a compile error on
Integer[] c = {3, 5}.
Your answer A is incorrect
The correct answer is C
Section 11.14 The protected Data and Methods
11.56 What modifier should you use on a class so that
a class in the same package can access it but a class
(including a subclass) in a different package cannot
access it?
A. public
B. private
C. protected
D. Use the default modifier.
Your answer A is incorrect
The correct answer is D
11.57 What modifier should you use on the members
of a class so that they are not accessible to another
class in a different package, but are accessible to any
subclasses in any package?
A. public
B. private
C. protected
D. Use the default modifier.
Your answer A is incorrect
[Link] 34/38
11/21/24, 2:13 AM Introduction to Java Programming
The correct answer is C
11.58 The visibility of these modifiers increases in this
order:
A. private, protected, none (if no
modifier is used), and public.
B. private, none (if no modifier is
used), protected, and public.
C. none (if no modifier is used),
private, protected, and public.
D. none (if no modifier is used),
protected, private, and public.
Your answer A is incorrect
The correct answer is B
11.59 A class design requires that a particular member
variable must be accessible by any subclasses of this
class, but otherwise not by classes which are not
members of the same package. What should be done
to achieve this?
A. The variable should be marked
public.
B. The variable should be marked
private.
C. The variable should be marked
protected.
D. The variable should have no
special access modifier.
E. The variable should be marked
private and an accessor method
provided.
Your answer A is incorrect
The correct answer is C
Explanation: See the section on the protected
modifier.
[Link] 35/38
11/21/24, 2:13 AM Introduction to Java Programming
11.60 Which of the following statements is false?
A. A public class can be accessed by
a class from a different package.
B. A private method cannot be
accessed by a class in a different
package.
C. A protected method can be accessed
by a subclass in a different
package.
D. A method with no visibility
modifier can be accessed by a class
in a different package.
Your answer A is incorrect
The correct answer is D
11.61 Which statements are most accurate regarding
the following classes?
class A {
private int i;
protected int j;
}
class B extends A {
private int k;
protected int m;
}
A. An object of B contains data
fields i, j, k, m.
B. An object of B contains data
fields j, k, m.
C. An object of B contains data
fields j, m.
D. An object of B contains data
fields k, m.
Your answer is correct
Explanation: The data fields in a superclass are
contained in a subclass. Whether the data fields in a
[Link] 36/38
11/21/24, 2:13 AM Introduction to Java Programming
superclass can be accessed in a subclass is a visibility
issue. A private data field in a superclass cannot be
directly accessed in a subclass, but the data field may
have the getter or setter methods, which can be used
to get or set a data field value.
11.62 Which statements are most accurate regarding
the following classes?
class A {
private int i;
protected int j;
}
class B extends A {
private int k;
protected int m;
// some methods omitted
}
A. In the class B, an instance method
can only access i, j, k, m.
B. In the class B, an instance method
can only access j, k, m.
C. In the class B, an instance method
can only access j, m.
D. In the class B, an instance method
can only access k, m.
Your answer A is incorrect
The correct answer is B
Section 11.15 Preventing Extending and Overriding
11.63 Which of the following classes cannot be
extended?
A. class A { }
B. class A { private A() { }}
C. final class A { }
D. class A { protected A() { }}
[Link] 37/38
11/21/24, 2:13 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
[Link] 38/38
11/21/24, 2:17 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 12 Exception Handling and Text
I/O
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 12.3 Exception Types
12.1 A Java exception is an instance of __________.
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
Your answer A is incorrect
The correct answer is D
[Link] 1/27
11/21/24, 2:17 AM Introduction to Java Programming
12.2 An instance of _________ describes system
errors. If this type of error occurs, there is little you
can do beyond notifying the user and trying to
terminate the program gracefully.
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
Your answer A is incorrect
The correct answer is C
12.3 An instance of _________ describes the errors
caused by your program and external circumstances.
These errors can be caught and handled by your
program.
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
Your answer A is incorrect
The correct answer is B
12.4 An instance of _________ describes
programming errors, such as bad casting, accessing
an out-of-bounds array, and numeric errors.
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
Your answer is correct
[Link] 2/27
11/21/24, 2:17 AM Introduction to Java Programming
12.5 The following code causes Java to throw
_________.
int number = Integer.MAX_VALUE + 1;
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. no exceptions
Your answer A is incorrect
The correct answer is E
Explanation: At present, Java does not throw integer
overflow exceptions. The future version of Java may
fix this problem to throw an over flow exception.
12.6 Instances of _________ are unchecked
exceptions.
A. RuntimeException
B. Exception
C. Error
D. Throwable
E. NumberFormatException
Your answer A is incorrect
The correct answer is ACE
Explanation: NumberFormatException is a subclass
of RuntimeException
12.7 What exception type does the following program
throw?
public class Test {
public static void main(String[] args) {
[Link](1 / 0);
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
[Link] 3/27
11/21/24, 2:17 AM Introduction to Java Programming
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
Your answer is correct
12.8 What exception type does the following program
throw?
public class Test {
public static void main(String[] args) {
int[] list = new int[5];
[Link](list[5]);
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
Your answer A is incorrect
The correct answer is B
12.9 What exception type does the following program
throw?
public class Test {
public static void main(String[] args) {
String s = "abc";
[Link]([Link](3));
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
Your answer A is incorrect
The correct answer is C
[Link] 4/27
11/21/24, 2:17 AM Introduction to Java Programming
12.10 What exception type does the following
program throw?
public class Test {
public static void main(String[] args) {
Object o = new Object();
String d = (String)o;
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. No exception
Your answer A is incorrect
The correct answer is D
12.11 What exception type does the following
program throw?
public class Test {
public static void main(String[] args) {
Object o = null;
[Link]([Link]());
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. ClassCastException
E. NullPointerException
Your answer A is incorrect
The correct answer is E
12.12 What exception type does the following
program throw?
[Link] 5/27
11/21/24, 2:17 AM Introduction to Java Programming
public class Test {
public static void main(String[] args) {
Object o = null;
[Link](o);
}
}
A. ArithmeticException
B. ArrayIndexOutOfBoundsException
C. StringIndexOutOfBoundsException
D. No exception
E. NullPointerException
Your answer A is incorrect
The correct answer is D
Section 12.4 More on Exception Handling
12.13 A method must declare to throw ________.
A. unchecked exceptions
B. checked exceptions
C. Error
D. RuntimeException
Your answer A is incorrect
The correct answer is B
12.14 Which of the following statements are true?
A. You use the keyword throws to
declare exceptions in the method
heading.
B. A method may declare to throw
multiple exceptions.
C. To throw an exception, use the key
word throw.
D. If a checked exception occurs in a
method, it must be either caught or
declared to be thrown from the
method.
[Link] 6/27
11/21/24, 2:17 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is ABCD
12.15 Analyze the following code:
public class Test {
public static void main(String[] args)
throws MyException {
[Link]("Welcome to Java");
}
}
class MyException extends Error {
}
A. You should not declare a class
that extends Error, because Error
raises a fatal error that
terminates the program.
B. You cannot declare an exception in
the main method.
C. You declared an exception in the
main method, but you did not throw
it.
D. The program has a compile error.
Your answer is correct
Explanation: When an exception of Error type
occurs, your program would terminate. Therefore,
you should not declare an exception that extends
Error. You declared an exception in the main method.
If you did not throw anything, that is fine.
12.16 Analyze the following code:
public class Test {
public static void main(String[] args) {
try {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
[Link] 7/27
11/21/24, 2:17 AM Introduction to Java Programming
int i = 0;
int y = 2 / i;
}
catch (Exception ex) {
[Link]("NumberFormatException");
}
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
}
}
A. The program displays
NumberFormatException.
B. The program displays
RuntimeException.
C. The program displays
NumberFormatException followed by
RuntimeException.
D. The program has a compile error.
Your answer A is incorrect
The correct answer is D
Explanation: catch (RuntimeException ex) should be
specified before catch (Exception ex).
12.17 Analyze the following program.
public class Test {
public static void main(String[] args) {
try {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
int i = 0;
int y = 2 / i;
[Link]("Welcome to Java");
}
catch (Exception ex) {
[Link](ex);
}
}
}
[Link] 8/27
11/21/24, 2:17 AM Introduction to Java Programming
A. An exception is raised due to
[Link](s);
B. An exception is raised due to 2 /
i;
C. The program has a compile error.
D. The program compiles and runs
without exceptions.
Your answer is correct
Explanation: Both (A) and (B) would cause
exception, but (A) occurred first, so the exception is
due to (A).
12.18 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
p();
[Link]("After the method
call");
}
catch (NumberFormatException ex) {
[Link]("NumberFormatException");
}
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
}
static void p() {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
int i = 0;
int y = 2 / i;
[Link]("Welcome to Java");
}
}
A. The program displays
NumberFormatException.
[Link] 9/27
11/21/24, 2:17 AM Introduction to Java Programming
B. The program displays
NumberFormatException followed by
After the method call.
C. The program displays
NumberFormatException followed by
RuntimeException.
D. The program has a compile error.
E. The program displays
RuntimeException.
Your answer is correct
Explanation: It should be A. The main method
invokes the method p. In p, [Link](s) causes
a NumberFormatException. The method p is now
terminated. The NumberFormatException exception
is handled in the main method. So
NumberFormatException is displayed.
12.19 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
p();
[Link]("After the method
call");
}
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
catch (Exception ex) {
[Link]("Exception");
}
}
static void p() throws Exception {
try {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
int i = 0;
int y = 2 / i;
[Link] 10/27
11/21/24, 2:17 AM Introduction to Java Programming
[Link]("Welcome to Java");
}
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
catch (Exception ex) {
[Link]("Exception");
}
}
}
A. The program displays
RuntimeException twice.
B. The program displays Exception
twice.
C. The program displays
RuntimeException followed by After
the method call.
D. The program displays Exception
followed by RuntimeException.
E. The program has a compile error.
Your answer A is incorrect
The correct answer is C
Section 12.5 The finally Clause
12.20 What is wrong in the following program?
public class Test {
public static void main (String[] args) {
try {
[Link]("Welcome to Java");
}
}
}
A. You cannot have a try block
without a catch block.
B. You cannot have a try block
without a catch block or a finally
block.
C. A method call that does not
declare exceptions cannot be placed
inside a try block.
[Link] 11/27
11/21/24, 2:17 AM Introduction to Java Programming
D. Nothing is wrong.
Your answer A is incorrect
The correct answer is B
12.21 What is displayed on the console when running
the following program?
public class Test {
public static void main (String[] args) {
try {
[Link]("Welcome to Java");
}
finally {
[Link]("The finally clause
is executed");
}
}
}
A. Welcome to Java
B. Welcome to Java followed by The
finally clause is executed in the
next line
C. The finally clause is executed
D. None of the above
Your answer A is incorrect
The correct answer is B
12.22 What is displayed on the console when running
the following program?
public class Test {
public static void main (String[] args) {
try {
[Link]("Welcome to Java");
return;
}
finally {
[Link]("The finally clause
is executed");
}
[Link] 12/27
11/21/24, 2:17 AM Introduction to Java Programming
}
}
A. Welcome to Java
B. Welcome to Java followed by The
finally clause is executed in the
next line
C. The finally clause is executed
D. None of the above
Your answer A is incorrect
The correct answer is B
Explanation: The return statement exits the method,
but before exiting the method, the finally clause is
executed.
12.23 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
[Link]("Welcome to Java");
int i = 0;
int y = 2 / i;
[Link]("Welcome to HTML");
}
finally {
[Link]("The finally clause
is executed");
}
}
}
A. Welcome to Java, then an error
message.
B. Welcome to Java followed by The
finally clause is executed in the
next line, then an error message.
C. The program displays three lines:
Welcome to Java, Welcome to HTML,
The finally clause is executed,
then an error message.
D. None of the above.
[Link] 13/27
11/21/24, 2:17 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is B
12.24 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
[Link]("Welcome to Java");
int i = 0;
double y = 2.0 / i;
[Link]("Welcome to HTML");
}
finally {
[Link]("The finally clause
is executed");
}
}
}
A. Welcome to Java.
B. Welcome to Java followed by The
finally clause is executed in the
next line.
C. The program displays three lines:
Welcome to Java, Welcome to HTML,
The finally clause is executed.
D. None of the above.
Your answer A is incorrect
The correct answer is C
Explanation: A floating number divided by 0 does
not raise an exception.
12.25 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
[Link]("Welcome to Java");
[Link] 14/27
11/21/24, 2:17 AM Introduction to Java Programming
int i = 0;
int y = 2/i;
[Link]("Welcome to Java");
}
catch (RuntimeException ex) {
[Link]("Welcome to Java");
}
finally {
[Link]("End of the block");
}
}
}
A. The program displays Welcome to
Java three times followed by End of
the block.
B. The program displays Welcome to
Java two times followed by End of
the block.
C. The program displays Welcome to
Java three times.
D. The program displays Welcome to
Java two times.
Your answer A is incorrect
The correct answer is B
12.26 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
[Link]("Welcome to Java");
int i = 0;
int y = 2/i;
[Link]("Welcome to Java");
}
catch (RuntimeException ex) {
[Link]("Welcome to Java");
}
finally {
[Link]("End of the block");
}
[Link] 15/27
11/21/24, 2:17 AM Introduction to Java Programming
[Link]("End of the block");
}
}
A. The program displays Welcome to
Java three times followed by End of
the block.
B. The program displays Welcome to
Java two times followed by End of
the block.
C. The program displays Welcome to
Java two times followed by End of
the block two times.
D. You cannot catch RuntimeException
errors.
Your answer A is incorrect
The correct answer is C
12.27 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
[Link]("Welcome to Java");
int i = 0;
int y = 2/i;
[Link]("Welcome to Java");
}
finally {
[Link]("End of the block");
}
[Link]("End of the block");
}
}
A. The program displays Welcome to
Java three times followed by End of
the block.
B. The program displays Welcome to
Java two times followed by End of
the block.
[Link] 16/27
11/21/24, 2:17 AM Introduction to Java Programming
C. The program displays Welcome to
Java two times followed by End of
the block two times.
D. The program displays Welcome to
Java and End of the block, and then
terminates because of an unhandled
exception.
Your answer A is incorrect
The correct answer is D
Section 12.6 When to Use Exceptions
12.28 Which of the following is not an advantage of
Java exception handling?
A. Java separates exception handling
from normal processing tasks.
B. Exception handling improves
performance.
C. Exception handling makes it
possible for the caller's caller to
handle the exception.
D. Exception handling simplifies
programming because the error-
reporting and error-handling code
can be placed at the catch block.
Your answer A is incorrect
The correct answer is B
12.29 Analyze the following code:
public class Test {
public static void main(String[] args) {
try {
int zero = 0;
int y = 2/zero;
try {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
[Link] 17/27
11/21/24, 2:17 AM Introduction to Java Programming
}
catch(Exception e) {
}
}
catch(RuntimeException e) {
[Link](e);
}
}
}
A. A try-catch block cannot be
embedded inside another try-catch
block.
B. A good programming practice is to
avoid nesting try-catch blocks,
because nesting makes programs
difficult to read. You can rewrite
the program using only one try-
catch block.
C. The program has a compile error
because Exception appears before
RuntimeException.
D. None of the above.
Your answer A is incorrect
The correct answer is B
Explanation: The best answer is b. This question
does not ask you what happens when you run the
program. If you run the program, a
RuntimeException would occur and it would be
caught be the last catch clause.
Section 12.7 Rethrowing Exceptions
12.30 What is displayed on the console when running
the following program?
public class Test {
public static void main(String[] args) {
try {
method();
[Link]("After the method
call");
}
[Link] 18/27
11/21/24, 2:17 AM Introduction to Java Programming
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
catch (Exception ex) {
[Link]("Exception");
}
}
static void method() throws Exception {
try {
String s = "5.6";
[Link](s); // Cause a
NumberFormatException
int i = 0;
int y = 2 / i;
[Link]("Welcome to Java");
}
catch (NumberFormatException ex) {
[Link]("NumberFormatException");
throw ex;
}
catch (RuntimeException ex) {
[Link]("RuntimeException");
}
}
}
A. The program displays
NumberFormatException twice.
B. The program displays
NumberFormatException followed by
After the method call.
C. The program displays
NumberFormatException followed by
RuntimeException.
D. The program has a compile error.
Your answer A is incorrect
The correct answer is C
Section 12.10 The File Class
12.31 What are the reasons to create an instance of the
File class?
[Link] 19/27
11/21/24, 2:17 AM Introduction to Java Programming
A. To determine whether the file
exists.
B. To obtain the properties of the
file such as whether the file can
be read, written, or is hidden.
C. To rename the file.
D. To delete the file.
E. To read/write data from/to a file
Your answer A is incorrect
The correct answer is ABCD
12.32 Which of the following is used to test if a file
c:\temp\[Link] exists?
A. new
File("c:\temp\[Link]").exists()
B. new
File("c:\\temp\\[Link]").exists()
C. new
File("c:\temp\[Link]").exist()
D. new
File("c:\\temp\\[Link]").exist()
E. None of the above.
Your answer A is incorrect
The correct answer is B
12.33 Which of the following statements creates an
instance of File on Window for the file c:\[Link]?
A. new File("c:\[Link]")
B. new File("c:\\[Link]")
C. new File("c:/[Link]")
D. new File("c://[Link]")
Your answer A is incorrect
The correct answer is B
[Link] 20/27
11/21/24, 2:17 AM Introduction to Java Programming
12.34 Which of the following statements are true?
A. If a file (e.g., c:\[Link]) does
not exist, new File("c:\\[Link]")
returns null.
B. If a directory (e.g., c:\liang)
does not exist, new
File("c:\liang") returns null.
C. If a file (e.g., c:\[Link]) does
not exist, new File("c:\\[Link]")
creates a new file named
c:\[Link].
D. If a directory (e.g., c:\liang)
does not exist, new
File("c:\liang") creates a new
directory named c:\liang.
E. None of the above.
Your answer A is incorrect
The correct answer is E
Section 12.11 Text I/O
12.35 Which class contains the method for checking
whether a file exists?
A. File
B. PrintWriter
C. Scanner
D. System
Your answer is correct
12.36 Which class do you use to write data into a text
file?
A. File
B. PrintWriter
C. Scanner
D. System
Your answer A is incorrect
[Link] 21/27
11/21/24, 2:17 AM Introduction to Java Programming
The correct answer is B
12.37 Which class do you use to read data from a text
file?
A. File
B. PrintWriter
C. Scanner
D. System
Your answer A is incorrect
The correct answer is C
12.38 Which method can be used to write data?
A. close
B. print
C. exist
D. rename
Your answer A is incorrect
The correct answer is B
12.39 Which method can be used to read a whole line
from the file?
A. next
B. nextLine
C. nextInt
D. nextDouble
Your answer A is incorrect
The correct answer is B
12.40 Which of the following statements are correct?
I:
try (PrintWriter output = new PrintWriter("[Link]");
[Link]("Welcome to Java");
}
[Link] 22/27
11/21/24, 2:17 AM Introduction to Java Programming
II:
try (PrintWriter output = new PrintWriter("[Link]");
Scanner input = new Scanner([Link]);)
{
[Link]([Link]());
}
III:
PrintWriter output;
try (output = new PrintWriter("[Link]");) {
[Link]("Welcome to Java");
}
IV:
try (PrintWriter output = new PrintWriter("[Link]");
[Link]("Welcome to Java");
}
finally {
[Link]();
}
A. I
B. II
C. III
D. IV
Your answer A is incorrect
The correct answer is AB
Explanation: III is wrong. You have to declare the
resource reference variable and create the resource
altogether in the try (?).
12.41 Which of the following statements are correct?
I:
File file = new File("[Link]");
try (Scanner input = new Scanner(file);) {
String line = [Link]();
}
II:
try (File file = new File("[Link]");
Scanner input = new Scanner(file);) {
String line = [Link]();
}
[Link] 23/27
11/21/24, 2:17 AM Introduction to Java Programming
III:
File file;
try (file = new File("[Link]");
Scanner input = new Scanner(file);) {
String line = [Link]();
}
IV:
File file;
Scanner input;
try (file = new File("[Link]");
input = new Scanner(file);) {
String line = [Link]();
}
A. I
B. II
C. III
D. IV
Your answer is correct
Explanation: File is not a subtype of AutoCloseable.
So it cannot be used to open a resource in a try-with-
resources.
12.42 Which method can be used to create an input
object for file [Link]?
A. new Scanner("[Link]")
B. new Scanner([Link])
C. new Scanner(new File("[Link]"))
D. new Scanner(File("[Link]"))
Your answer A is incorrect
The correct answer is C
12.43 Suppose you enter 34.3 57.8 789, then press the
ENTER key. Analyze the following code.
Scanner input = new Scanner([Link]);
int v1 = [Link]();
[Link] 24/27
11/21/24, 2:17 AM Introduction to Java Programming
int v2 = [Link]();
String line = [Link]();
A. After the last statement is
executed, v1 is 34.
B. The program has a runtime error
because 34.3 is not an integer.
C. After the last statement is
executed, line contains characters
'7', '8', '9', '\n'.
D. After the last statement is
executed, line contains characters
'7', '8', '9'.
Your answer A is incorrect
The correct answer is B
Explanation: See discussions in Section 12.11.3.
12.44 Suppose you enter 34.3 57.8 789, then press the
ENTER key. Analyze the following code.
Scanner input = new Scanner([Link]);
double v1 = [Link]();
double v2 = [Link]();
String line = [Link]();
A. After the last statement is
executed, line contains characters
'7', '8', '9'.
B. After the last statement is
executed, line contains characters
'7', '8', '9', '\n'.
C. After the last statement is
executed, line contains characters
' ', '7', '8', '9', '\n'.
D. After the last statement is
executed, line contains characters
' ', '7', '8', '9'.
Your answer A is incorrect
The correct answer is D
Explanation: See discussions in Section 12.11.3.
[Link] 25/27
11/21/24, 2:17 AM Introduction to Java Programming
12.45 Suppose you enter 34.3, the ENTER key, 57.8,
the ENTER key. Analyze the following code.
Line 1 Scanner input = new Scanner([Link]);
Line 2 double v1 = [Link]();
Line 3 double v2 = [Link]();
Line 4 String line = [Link]();
A. After line 2 is executed, v1 is
34.3.
B. After line 3 is executed, v2 is
57.8.
C. After line 4 is executed, line
contains an empty string.
D. After line 4 is executed, line is
null.
E. After line 4 is executed, line
contains character "\n".
Your answer A is incorrect
The correct answer is ABC
Explanation: See discussions in Section 12.11.3.
12.46 Suppose you enter 34.3, the ENTER key, 57.8,
the ENTER key, abc, the Enter key. Analyze the
following code.
Line 1 Scanner input = new Scanner([Link]);
Line 2 double v1 = [Link]();
Line 3 double v2 = [Link]();
Line 4 String line = [Link]();
A. After line 2 is executed, v1 is
34.3.
B. After line 3 is executed, v2 is
57.8.
C. After line 4 is executed, line
contains an empty string.
D. After line 4 is executed, line is
null.
[Link] 26/27
11/21/24, 2:17 AM Introduction to Java Programming
E. After line 4 is executed, line
contains character "abc".
Your answer A is incorrect
The correct answer is ABC
Explanation: See discussions in Section 12.11.3.
12.47 Which method can be used to create an output
object for file [Link]?
A. new PrintWriter("[Link]")
B. new PrintWriter([Link])
C. new PrintWriter(new
File("[Link]"))
D. new PrintWriter(File("[Link]"))
Your answer A is incorrect
The correct answer is AC
Section 12.12 Reading Data from the Web
12.48 To create an InputStream to read from a file on a
Web server, you use the method __________ in the
URL class.
A. getInputStream();
B. obtainInputStream();
C. openStream();
D. connectStream();
Your answer A is incorrect
The correct answer is C
[Link] 27/27
11/21/24, 2:20 AM Introduction to Java Programming
Introduction to Java Programming,
Includes Data Structures, Eleventh
Edition, Y. Daniel Liang
This quiz is for students to practice. A large number of additional
quiz is available for instructors using Quiz Generator from the
Instructor's Resource Website. Videos for Java, Python, and C++
can be found at [Link]
Chapter 13 Abstract Classes and
Interfaces
Please send suggestions and errata to Dr. Liang at
[Link]@[Link]. Indicate which book and
edition you are using. Thanks!
Section 13.2 Abstract Classes
13.1 Which of the following class definitions defines a
legal abstract class?
A. class A { abstract void
unfinished() { } }
B. class A { abstract void
unfinished(); }
C. abstract class A { abstract void
unfinished(); }
D. public class abstract A { abstract
void unfinished(); }
[Link] 1/23
11/21/24, 2:20 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
Explanation: In A and B, abstract keyword is missing
for the class. In D, class and abstract are in a wrong
order. The correct answer is C.
13.2 Which of the following declares an abstract
method in an abstract Java class?
A. public abstract method();
B. public abstract void method();
C. public void abstract method();
D. public void method() {}
E. public abstract void method() {}
Your answer A is incorrect
The correct answer is B
Explanation: In A, the method has no return type. In
C, void and abstract are in a wrong order. In D, the
abstract keyword is missing. In E, the body {} should
be removed. The correct answer is B.
13.3 Which of the following statements regarding
abstract methods is false?
A. An abstract class can have
instances created using the
constructor of the abstract class.
B. An abstract class can be extended.
C. A subclass of a non-abstract
superclass can be abstract.
D. A subclass can override a concrete
method in a superclass to declare
it abstract.
E. An abstract class can be used as a
data type.
Your answer is correct
[Link] 2/23
11/21/24, 2:20 AM Introduction to Java Programming
Explanation: A is wrong because you cannot create
an instance using the constructor from an abstract
class.
13.4 Which of the following statements regarding
abstract methods is false?
A. Abstract classes have
constructors.
B. A class that contains abstract
methods must be abstract.
C. It is possible to declare an
abstract class that contains no
abstract methods.
D. An abstract method cannot be
contained in a nonabstract class.
E. A data field can be declared
abstract.
Your answer A is incorrect
The correct answer is E
Explanation: E is wrong, because a data field cannot
be declared abstract. Only methods and classes can
be declared abstract.
13.5 Suppose A is an abstract class, B is a concrete
subclass of A, and both A and B have a no-arg
constructor. Which of the following is correct?
A. A a = new A();
B. A a = new B();
C. B b = new A();
D. B b = new B();
Your answer A is incorrect
The correct answer is BD
Explanation: Since B is a concrete class with a no-
arg constructor, d is correct. Since an instance of B is
also an instance of A, b is also correct.
[Link] 3/23
11/21/24, 2:20 AM Introduction to Java Programming
13.6 What is the output of running class Test?
public class Test {
public static void main(String[] args) {
new Circle9();
}
}
public abstract class GeometricObject {
protected GeometricObject() {
[Link]("A");
}
protected GeometricObject(String color,
boolean filled) {
[Link]("B");
}
}
public class Circle9 extends GeometricObject {
/** No-arg constructor */
public Circle9() {
this(1.0);
[Link]("C");
}
/** Construct circle with a specified
radius */
public Circle9(double radius) {
this(radius, "white", false);
[Link]("D");
}
/** Construct a circle with specified
radius, filled, and color */
public Circle9(double radius, String color,
boolean filled) {
super(color, filled);
[Link]("E");
}
}
A. ABCD
B. BACD
C. CBAE
D. AEDC
E. BEDC
[Link] 4/23
11/21/24, 2:20 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is E
Section 13.3 Case Study: the Abstract Number Class
13.7 The [Link] and its subclasses are
introduced in Chapter 11. Analyze the following
code.
Number numberRef = new Integer(0);
Double doubleRef = (Double)numberRef;
A. There is no such class named
Integer. You should use the class
Int.
B. The compiler detects that
numberRef is not an instance of
Double.
C. A runtime class casting exception
occurs, since numberRef is not an
instance of Double.
D. The program runs fine, since
Integer is a subclass of Double.
E. You can convert an int to double,
so you can cast an Integer instance
to a Double instance.
Your answer A is incorrect
The correct answer is C
13.8 Analyze the following code.
Number[] numberArray = new Integer[2];
numberArray[0] = new Double(1.5);
A. You cannot use Number as a data
type since it is an abstract class.
B. Since each element of numberArray
is of the Number type, you cannot
assign an Integer object to it.
[Link] 5/23
11/21/24, 2:20 AM Introduction to Java Programming
C. Since each element of numberArray
is of the Number type, you cannot
assign a Double object to it.
D. At runtime, new Integer[2] is
assigned to numberArray. This makes
each element of numberArray an
Integer object. So you cannot
assign a Double object to it.
Your answer A is incorrect
The correct answer is D
13.9 Analyze the following code. Which of the
following statements is correct?
public class Test {
public static void main(String[] args) {
Number x = new Integer(3);
[Link]([Link]());
[Link]([Link](new
Integer(4)));
}
}
A. The program has a compile error
because an Integer instance cannot
be assigned to a Number variable.
B. The program has a compile error
because intValue is an abstract
method in Number.
C. The program has a compile error
because x does not have the
compareTo method.
D. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is C
13.10 Analyze the following code. Which of the
following statements is correct?
[Link] 6/23
11/21/24, 2:20 AM Introduction to Java Programming
public class Test {
public static void main(String[] args) {
Number x = new Integer(3);
[Link]([Link]());
[Link]((Integer)[Link](new
Integer(4)));
}
}
A. The program has a compile error
because an Integer instance cannot
be assigned to a Number variable.
B. The program has a compile error
because intValue is an abstract
method in Number.
C. The program has a compile error
because x cannot be cast into
Integer.
D. The program has a compile error
because the member access operator
(.) is executed before the casting
operator.
E. The program compiles and runs
fine.
Your answer A is incorrect
The correct answer is D
13.11 Which of the following statements is incorrect?
A. Integer i = 4.5;
B. Double i = 4.5;
C. Object i = 4.5;
D. Number i = 4.5;
Your answer is correct
Explanation: i is an Integer. You cannot assign 4.5 to
i. A is incorrect. B, C, and D are correct. 4.5 is
autoboxed to new Double(4.5). A Double object is an
instance of Object and Double.
[Link] 7/23
11/21/24, 2:20 AM Introduction to Java Programming
Section 13.4 Case Study: Calendar and
GregorianCalendar
13.12 The [Link] and
[Link] classes are introduced in
Chapter 11. Analyze the following code. Which of
the following statements is correct?
1. import [Link].*;
2. public class Test {
3. public static void main(String[] args) {
4. Calendar[] calendars = new Calendar[10];
5. calendars[0] = new Calendar();
6. calendars[1] = new GregorianCalendar();
7. }
8. }
A. The program has a compile error on
Line 4 because [Link]
is an abstract class.
B. The program has a compile error on
Line 5 because [Link]
is an abstract class.
C. The program has a compile error on
Line 6 because Calendar[1] is not
of a GregorianCalendar type.
D. The program has no compile errors.
Your answer A is incorrect
The correct answer is B
Explanation: (A) is incorrect since it is OK to use
abstract class as data type for arrays. new
Calendar[10] does not create Calendar objects. It just
creates an array with 10 elements, each of which can
reference to a Calendar object. (B) is correct since
you cannot create an object from an abstract class.
(C) is incorrect since it is fine to create a
GregorianCalendar object and assign its reference to
a variable of its superclass type.
13.13 Assume Calendar calendar = new
GregorianCalendar(). __________ returns the month
[Link] 8/23
11/21/24, 2:20 AM Introduction to Java Programming
of the year.
A. [Link]([Link])
B.
[Link](Calendar.MONTH_OF_YEAR)
C.
[Link](Calendar.WEEK_OF_MONTH)
D.
[Link](Calendar.WEEK_OF_YEAR)
Your answer is correct
Explanation: B is wrong since
Calendar.MONTH_OF_YEAR is not a valid field.
13.14 Assume Calendar calendar = new
GregorianCalendar(). __________ returns the week
of the year.
A. [Link]([Link])
B.
[Link](Calendar.MONTH_OF_YEAR)
C.
[Link](Calendar.WEEK_OF_MONTH)
D.
[Link](Calendar.WEEK_OF_YEAR)
Your answer A is incorrect
The correct answer is D
13.15 Assume Calendar calendar = new
GregorianCalendar(). __________ returns the
number of days in a month.
A. [Link]([Link])
B.
[Link](Calendar.MONTH_OF_YEAR)
C.
[Link](Calendar.WEEK_OF_MONTH)
D.
[Link](Calendar.WEEK_OF_YEAR)
[Link] 9/23
11/21/24, 2:20 AM Introduction to Java Programming
E.
[Link](Calendar.DAY_OF_MO
Your answer A is incorrect
The correct answer is E
Section 13.5 Interfaces
13.16 Which of the following is a correct interface?
A. interface A { void print() { }; }
B. abstract interface A { print(); }
C. abstract interface A { abstract
void print() { };}
D. interface A { void print();}
Your answer A is incorrect
The correct answer is D
Explanation: In A, the print() method in the interface
is a concrete method. In B and C, the abstract
keyword is used before the interface, which is wrong.
The correct answer is D.
13.17 Which of the following are incorrect?
A. An abstract class contains
constructors.
B. The constructors in an abstract
class should be protected.
C. The constructors in an abstract
class are private.
D. You may declare a final abstract
class.
E. An interface may contain
constructors.
Your answer A is incorrect
The correct answer is CDE
Explanation: A and B are correct. C is wrong. D is
wrong. E is wrong because an interface does not
have constructors.
[Link] 10/23
11/21/24, 2:20 AM Introduction to Java Programming
13.18 _______ is not a reference type.
A. A class type
B. An interface type
C. An array type
D. A primitive type
Your answer A is incorrect
The correct answer is D
Explanation: Objects and arrays are reference types.
Primitive types are not.
13.19 Show the output of running the class Test in the
following code lines:
interface A {
}
class C {
}
class B extends D implements A {
}
public class Test {
public static void main(String[] args) {
B b = new B();
if (b instanceof A)
[Link]("b is an instance of
A");
if (b instanceof C)
[Link]("b is an instance of
C");
}
}
class D extends C {
}
A. Nothing.
B. b is an instance of A.
C. b is an instance of C.
[Link] 11/23
11/21/24, 2:20 AM Introduction to Java Programming
D. b is an instance of A followed by
b is an instance of C.
Your answer A is incorrect
The correct answer is D
13.20 Suppose A is an interface, B is a concrete class
with a no-arg constructor that implements A. Which
of the following is correct?
A. A a = new A();
B. A a = new B();
C. B b = new A();
D. B b = new B();
Your answer A is incorrect
The correct answer is BD
Explanation: Since B is a concrete class with a no-
arg constructor, d is correct. Since an instance of B is
also an instance of A, b is also correct.
Section 13.6 The Comparable Interface
13.21 Analyze the following code:
public class Test1 {
public Object max(Object o1, Object o2) {
if ((Comparable)[Link](o2) >= 0) {
return o1;
}
else {
return o2;
}
}
}
A. The program has a compile error
because Test1 does not have a main
method.
B. The program has a compile error
because o1 is an Object instance
[Link] 12/23
11/21/24, 2:20 AM Introduction to Java Programming
and it does not have the compareTo
method.
C. The program has a compile error
because you cannot cast an Object
instance o1 into Comparable.
D. The program would compile if
((Comparable)[Link](o2) >= 0)
is replaced by
(((Comparable)o1).compareTo(o2) >=
0).
Your answer A is incorrect
The correct answer is BD
Explanation: The . operator is performed before
casting.
13.22 Which of the following statements are true?
A. The String class implements
Comparable.
B. The Date class implements
Comparable.
C. The Double class implements
Comparable.
D. The BigInteger class implements
Comparable.
Your answer A is incorrect
The correct answer is ABCD
Explanation: Many classes in the Java API
implements the Comparable interface if the objects
of the class can be compared. Strings, Dates,
Doubles, and BigIntegers can all be compared. These
classes implement the Comparable interface.
13.23 Analyze the following code.
1. public class Test {
2. public static void main(String[] args) {
3. Fruit[] fruits = {new Fruit(2), new Fruit(3), new
[Link] 13/23
11/21/24, 2:20 AM Introduction to Java Programming
4. [Link](fruits);
5. }
6. }
class Fruit {
private double weight;
public Fruit(double weight) {
[Link] = weight;
}
}
A. The program has a compile error
because the Fruit class does not
have a no-arg constructor.
B. The program has a runtime error on
Line 3 because the Fruit class does
not have a no-arg constructor.
C. The program has a compile error on
Line 4 because the Fruit class does
not implement the
[Link] interface and
the Fruit objects are not
comparable.
D. The program has a runtime error on
Line 4 because the Fruit class does
not implement the
[Link] interface and
the Fruit objects are not
comparable.
Your answer A is incorrect
The correct answer is D
Explanation: (A) and (B) are incorrect since it is OK
to define a class without a no-arg constructor. (C) is
incorrect since it is OK to pass fruits to
[Link](Object[]) without compile errors. (D) is
correct because the [Link] method requires the
objects in the array to be comparable and their class
must implement the [Link] interface.
Section 13.7 The Cloneable Interface
[Link] 14/23
11/21/24, 2:20 AM Introduction to Java Programming
13.24 Analyze the following code.
public class Test {
public static void main(String[] args) {
[Link] x = new [Link]();
[Link] y = [Link]();
[Link](x = y);
}
}
A. A [Link] object is not
cloneable.
B. x = y in [Link](x = y)
causes a compile error because you
cannot have an assignment statement
inside a statement.
C. x = y in [Link](x = y)
causes a runtime error because you
cannot have an assignment statement
inside a statement.
D. The program has a compile error
because the return type of the
clone() method is [Link].
Your answer A is incorrect
The correct answer is D
Explanation: (A) is wrong because Date implements
and Cloneable and overrides the clone() method. (B)
and (C) are wrong because x = y is an assignment
expression, which assigns y to x. (D) is correct. You
have to cast it into Date in order to assign it to y.
13.25 The output from the following code is
__________.
[Link]<String> list = new [Link]
();
[Link]("New York");
[Link]<String> list1 = ([Link]
([Link]());
[Link]("Atlanta");
[Link]("Dallas");
[Link](list1);
[Link] 15/23
11/21/24, 2:20 AM Introduction to Java Programming
A. [New York]
B. [New York, Atlanta]
C. [New York, Atlanta, Dallas]
D. [New York, Dallas]
Your answer A is incorrect
The correct answer is D
Explanation: The code added New York to list and
cloned list1 from list. list1 now contains New York.
Dallas is added to list1. So list1 contains New Your
and Dallas.
13.26 The GeometricObject and Circle classes are
defined in this chapter. Analyze the following code.
Which statements are correct?
public class Test {
public static void main(String[] args) {
GeometricObject x = new Circle(3);
GeometricObject y = (Circle)([Link]());
[Link](x);
[Link](y);
}
}
A. The program has a compile error
because the clone() method is
protected in the Object class.
B. After you override the clone()
method and make it public in the
Circle class, the problem can
compile and run just fine, but y is
null if Circle does not implement
the Cloneable interface.
C. To enable a Circle object to be
cloned, the Circle class has to
override the clone() method and
implement the [Link]
interface.
D. If GeometricObject implements
Cloneable and Circle overrides the
clone() method, the clone() method
[Link] 16/23
11/21/24, 2:20 AM Introduction to Java Programming
will work fine to clone Circle
objects.
Your answer A is incorrect
The correct answer is ABCD
Section 13.8 Interfaces vs. Abstract Classes
13.27 Which of the following statements is false?
A. If you compile an interface
without errors, a .class file is
created for the interface.
B. If you compile a class without
errors but with warnings, a .class
file is created.
C. If you compile a class with
errors, a .class file is created
for the class.
D. If you compile an interface
without errors, but with warnings,
a .class file is created for the
interface.
Your answer A is incorrect
The correct answer is C
Explanation: A .class file is created for each Java
class and interface. But if it has a compile error, no
.class file is created.
13.28 Which of the following statements are true?
A. Inheritance models the is-a
relationship between two classes.
B. A strong is-a relationship
describes a direct inheritance
relationship between two classes.
C. A weak is-a relationship describes
that a class has certain
properties.
[Link] 17/23
11/21/24, 2:20 AM Introduction to Java Programming
D. A strong is-a relationship can be
represented using class
inheritance.
E. A weak is-a relationship can be
represented using interfaces.
Your answer A is incorrect
The correct answer is ABCDE
13.29 What is the best suitable relationship between
Employee and Faculty?
A. Composition
B. Aggregation
C. Inheritance
D. None.
Your answer A is incorrect
The correct answer is C
13.30 Assume an employee can work for only one
company. What is the best suitable relationship
between Company and Employee?
A. None
B. Aggregation
C. Inheritance
D. Composition
Your answer A is incorrect
The correct answer is D
13.31 The relationship between an interface and the
class that implements it is
A. Composition
B. Aggregation
C. Inheritance
D. None
[Link] 18/23
11/21/24, 2:20 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is C
Section 13.9 Case Study: The Rational Class
13.32 The Rational class in this chapter is defined as a
subclass of [Link]. Which of the
following expressions is correct?
A. [Link]();
B. [Link]("5/4");
C. new Rational(5, 4).doubleValue();
D. new Rational(5,
4).toDoubleValue();
E. new Rational(5, 4).intValue();
Your answer A is incorrect
The correct answer is CE
Explanation: A is wrong, because the doubleValue()
method is an instance method. B is wrong for two
reasons: 1. the doubleValue() method is an instance
method; 2. the doubleValue() method does not have
arguments. D is wrong becasue there is no method
named toDoubleValue().
13.33 The Rational class in this chapter extends
[Link] and implements
[Link]. Analyze the following code.
1. public class Test {
2. public static void main(String[] args) {
3. Number[] numbers = {new Rational(1, 2), new Integ
4. [Link](numbers);
5. }
6. }
A. The program has a compile error
because numbers is declared as
Number[], so you cannot assign {new
Rational(1, 2), new Integer(4), new
Double(5.6)} to it.
[Link] 19/23
11/21/24, 2:20 AM Introduction to Java Programming
B. The program has a runtime error
because numbers is declared as
Number[], so you cannot assign {new
Rational(1, 2), new Integer(4), new
Double(5.6)} to it.
C. The program has a compile error
because numbers is declared as
Number[], so you cannot pass it to
[Link](Object[]).
D. The program has a runtime error
because the compareTo methods in
Rational, Integer, and Double
classes do not compare the value of
one type with a value of another
type.
Your answer A is incorrect
The correct answer is D
Explanation: (A) and (B) are incorrect because
Rational, Integer, and Double are subclasses of
Number and any instances of these classes can be
elements of the Number[] array. (C) is incorrect
because it is fine to pass an instance of Number[] to a
parameter of the Object[] type. (D) is correct because
the compareTo method in Rational, Integer, Double
only compare two Rational objects, two Integer
objects, or two Double objects.
Section 13.10 Class Design Guidelines
13.34 Which of the following statements are true?
A. A class should describe a single
entity and all the class operations
should logically fit together to
support a coherent purpose.
B. A class should always contain a
no-arg constructor.
C. The constructors must always be
public.
D. The constructors may be protected.
[Link] 20/23
11/21/24, 2:20 AM Introduction to Java Programming
Your answer A is incorrect
The correct answer is AD
Explanation: (B) is not true. Most classes have a no-
arg constructor. But sometimes, it does not make any
sense to provide a no-arg constructor. For example,
StringTokenizer does not have a no-arg constructor.
(C) is not true. For example, the constructor in the
Math class is private to prevent creating instances
from the class, because there is no need to create
instances for the Math class since all methods are
static in Math. The constructors for abstract classes
should be protected in most cases.
13.35 Which of the following is poor design?
A. A data field is derived from other
data fields in the same class.
B. A method must be invoked
after/before invoking another
method in the same class.
C. A method is an instance method,
but it does not reference any
instance data fields or invoke
instance methods.
D. A parameter is passed from a
constructor to initialize a static
data field.
Your answer A is incorrect
The correct answer is ABCD
Explanation: A is not good because there is no need
to define the data field if it can be derived from other
data fields. B is not good because it is highly
problematic to impose any order for invoking the
methods. C is a bad design because in this case the
method should be defined as static. D is not good
because a static data field is now tied to the creation
of a specific object, which should not be the case.
[Link] 21/23
11/21/24, 2:20 AM Introduction to Java Programming
13.36 Polymorphism means ______________.
A. that data fields should be
declared private
B. that a class can extend another
class
C. that a variable of supertype can
refer to a subtype object
D. that a class can contain another
class
Your answer A is incorrect
The correct answer is C
13.37 Encapsulation means ______________.
A. that data fields should be
declared private
B. that a class can extend another
class
C. that a variable of supertype can
refer to a subtype object
D. that a class can contain another
class
Your answer is correct
13.38 Inheritance means ______________.
A. that data fields should be
declared private
B. that a class can extend another
class
C. that a variable of supertype can
refer to a subtype object
D. that a class can contain another
class
Your answer A is incorrect
The correct answer is B
[Link] 22/23
11/21/24, 2:20 AM Introduction to Java Programming
13.39 Composition means ______________.
A. that data fields should be
declared private
B. that a class extends another class
C. that a variable of supertype
refers to a subtype object
D. that a class contains a data field
that references another object
Your answer A is incorrect
The correct answer is D
[Link] 23/23