0% found this document useful (0 votes)
15 views99 pages

Multiple Choice Question Bank With Java

The document is a comprehensive question bank for practicing Java programming concepts, covering topics such as elementary programming, variables, loops, methods, arrays, and object-oriented programming. It includes multiple-choice questions, case studies, and explanations related to Java syntax and best practices. This resource is designed to aid learners in mastering Java programming through structured practice.

Uploaded by

cyanleafplayz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views99 pages

Multiple Choice Question Bank With Java

The document is a comprehensive question bank for practicing Java programming concepts, covering topics such as elementary programming, variables, loops, methods, arrays, and object-oriented programming. It includes multiple-choice questions, case studies, and explanations related to Java syntax and best practices. This resource is designed to aid learners in mastering Java programming through structured practice.

Uploaded by

cyanleafplayz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STEM EDUCATION METAVERSE, IRELAND

Programming with Java


Multiple Choice Practice Question Bank
Contents
Elementary Programming ..................................................................................................................... 4
Writing a Simple Program ................................................................................................................. 4
Reading Input from the Console ...................................................................................................... 4
Identifiers ........................................................................................................................................... 5
Variables ............................................................................................................................................ 5
Named Constants ............................................................................................................................. 6
Naming Conventions ........................................................................................................................ 7
Numeric Types ................................................................................................................................... 7
Exponent Operations ........................................................................................................................ 8
Numeric Literals ................................................................................................................................ 9
Evaluating Expressions and Operator Precedence ...................................................................... 10
Case Study: Displaying the Current Time ..................................................................................... 11
Augmented Assignment Operators ............................................................................................... 12
Numeric Type Conversions ............................................................................................................ 15
Selections ............................................................................................................................................ 18
boolean Data Type .......................................................................................................................... 18
if Statements.................................................................................................................................... 18
Two-Way if-else Statements .......................................................................................................... 19
Nested if and Multi-Way if-else Statements ................................................................................. 19
Common Errors and Pitfalls ........................................................................................................... 20
Generating Random Numbers ....................................................................................................... 21
Case Study: Computing Body Mass Index .................................................................................... 22
Case Study: Computing Taxes ....................................................................................................... 23
Logical Operators ............................................................................................................................ 23
Determining Leap Year ................................................................................................................... 24
switch Statements .......................................................................................................................... 26
Conditional Expressions ................................................................................................................. 26
Operator Precedence and Associativity ........................................................................................ 27
Mathematical Functions, Characters, and Strings .......................................................................... 29
Trigonometric Methdos ................................................................................................................... 29
The Rounding Methods ................................................................................................................... 29
Unicode and ASCII Code ................................................................................................................ 30
Escape Sequences for Special Characters .................................................................................. 30
Casting between char and Numeric Types ................................................................................... 31

[Link]
Comparing and Testing Characters ............................................................................................... 32
Getting Characters from a String ................................................................................................... 32
Converting Strings ........................................................................................................................... 33
Comparing Strings........................................................................................................................... 33
Finding a Character or a Substring in a String ............................................................................... 34
Conversions between Strings and Numbers ................................................................................ 35
Formatting Console Output ........................................................................................................... 35
Loops .................................................................................................................................................... 37
The while Loop ................................................................................................................................. 37
Case Study: Guessing Numbers .................................................................................................... 37
Controlling a Loop with User Confirmation or a Sentinel Value ................................................. 38
The do-while Loop ........................................................................................................................... 38
The for Loop ..................................................................................................................................... 39
Which Loop to Use? ........................................................................................................................ 42
Nested Loops................................................................................................................................... 43
Minimizing Numerical Errors .......................................................................................................... 44
Case Studies .................................................................................................................................... 44
Keywords break and continue ........................................................................................................ 45
Case Study: Checking Palindromes .............................................................................................. 47
Case Study: Displaying Prime Numbers ....................................................................................... 48
Methods ............................................................................................................................................... 50
Defining a Method ........................................................................................................................... 50
Calling a Method.............................................................................................................................. 50
Passing Parameters by Values ....................................................................................................... 53
Overloading Methods ...................................................................................................................... 54
The Scope of Variables ................................................................................................................... 56
Method Abstraction and Stepwise Refinement ............................................................................ 57
Single-Dimensional Arrays ................................................................................................................. 58
Array Basics ..................................................................................................................................... 58
Case Study: Analyzing Numbers .................................................................................................... 59
Case Study: Deck of Cards ............................................................................................................. 60
Copying Arrays ................................................................................................................................. 63
Passing Arrays to Methods ............................................................................................................. 66
Sorting Arrays................................................................................................................................... 71
The Arrays Class .............................................................................................................................. 71

[Link]
Command-Line Arguments ............................................................................................................ 72
Multidimensional Arrays ..................................................................................................................... 74
Two-Dimensional Array Basics ...................................................................................................... 74
Processing Two-Dimensional Arrays ............................................................................................. 76
Passing Two-Dimensional Arrays to Methods .............................................................................. 78
Multidimensional Arrays ................................................................................................................. 79
Objects and Classes ........................................................................................................................... 81
Defining Classes for Objects .......................................................................................................... 81
Constructing Objects Using Constructors.................................................................................... 81
Accessing Objects via Reference Variables ................................................................................. 83
Using Classes From the Java Library ............................................................................................. 86
Visibility Modifiers ........................................................................................................................... 90
Data Field Encapsulation ............................................................................................................... 91
Passing Objects to Methods........................................................................................................... 92
Array of Objects ............................................................................................................................... 95
Immutable Objects and Classes ................................................................................................... 95
Scope of Variables .......................................................................................................................... 95
The this Keyword ............................................................................................................................. 97

[Link]
Elementary Programming
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

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

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]();
2.4 The following code fragment reads in two numbers:

Scanner input = new Scanner([Link]);


int i = [Link]();
double d = [Link]();

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.

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) {

[Link]
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);
}
}
A. 1.0
B. 2.0
C. 3.0
D. 4.0

Identifiers
2.6 Every letter in a Java keyword is in lowercase?
A. true
B. false

2.7 Which of the following is a valid identifier?


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

Variables
2.8 Which of the following are correct names for variables according to Java naming
conventions?
A. radius
B. Radius
C. RADIUS
D. findArea
E. FindArea

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;

[Link]
Section 2.6 Assignment Statements and Assignment Expressions
2.10 ____________ is the Java assignment operator.
A. ==
B. :=
C. =
D. =:

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;

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;

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;

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

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

[Link]
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
E. class

Numeric Types
2.17 Which of these data types requires the most amount of memory?
A. long
B. int
C. short
D. 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

Section 2.9.3 Numeric Operators


2.19 What is the result of 45 / 4?
A. 10
B. 11
C. 11.25
D. 12

2.20 Which of the following expression results in a value 1?


A. 2 % 1
B. 15 % 4
C. 25 % 5
D. 37 % 6

2.21 25 % 1 is _____
A. 1
B. 2
C. 3
D. 4
E. 0

[Link]
2.22 -25 % 5 is _____
A. 1
B. 2
C. 3
D. 4
E. 0

2.23 24 % 5 is _____
A. 1
B. 2
C. 3
D. 4
E. 0
2.24 -24 % 5 is _____
A. -1
B. -2
C. -3
D. -4
E. 0
2.25 -24 % -5 is _____
A. 3
B. -3
C. 4
D. -4
E. 0

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

2.27 [Link](2, 3) returns __________.


A. 9
B. 8
C. 9.0
D. 8.0

[Link]
2.28 [Link](4, 1 / 2) returns __________.
A. 2
B. 2.0
C. 0
D. 1.0
E. 1

2.29 [Link](4, 1.0 / 2) returns __________.


A. 2
B. 2.0
C. 0
D. 1.0
E. 1

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)

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;

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.

[Link]
2.33 Which of the following is incorrect?
A. 1_2
B. 0.4_56
C. 1_200_229
D. _4544

2.34 Which of the following are the same as 1545.534?


A. 1.545534e+3
B. 0.1545534e+4
C. 1545534.0e-3
D. 154553.4e-2

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;

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

[Link]
Case Study: Displaying the Current Time
2.37 The [Link]() returns ________________ .
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).

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

2.39 To obtain the current minute, use _________.


A. [Link]() % 3600
B. [Link]() % 60
C. [Link]() / 1000 % 60
D. [Link]() / 1000 / 60 % 60
E. [Link]() / 1000 / 60 / 60 % 24

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

[Link]
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;

2.42 To add number to sum, you write (Note: Java is case-sensitive)


A. number += sum;
B. number = sum + number;
C. sum = Number + sum;
D. sum += number;
E. sum = sum + number;

2.43 Suppose x is 1. What is x after x += 2?


A. 0
B. 1
C. 2
D. 3
E. 4

2.44 Suppose x is 1. What is x after x -= 1?


A. 0
B. 1
C. 2
D. -1
E. -2

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]
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.

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

Increment and Decrement Operators


2.48 Are the following four statements equivalent?
number += 1;
number = number + 1;
number++;
++number;
A. Yes
B. No

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

[Link]
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);


}
}
A. 0
B. 1
C. 5
D. 6

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.

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.

[Link]
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;

2.54 Which of the following expressions will yield 0.5?


A. 1 / 2
B. 1.0 / 2
C. (double) (1 / 2)
D. (double) 1 / 2
E. 1 / 2.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

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;

2.57 What is the value of (double)5/2?


A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0
2.58 What is the value of (double)(5/2)?
A. 2
B. 2.5
C. 3
D. 2.0
E. 3.0

[Link]
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

2.60 The expression (int)(76.0252175 * 100) / 100 evaluates to _________.


A. 76.02
B. 76
C. 76.0252175
D. 76.03

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
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

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
C. Design
D. Implementation
E. Testing
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);
}
}

[Link]
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 continues to execute because Java does not
report errors on underflow.

[Link]
Selections
boolean Data Type
3.1 The "less than or equal to" comparison operator in Java is __________.
A. <
B. <=
C. =<
D. <<
E. !=

3.2 The equal comparison operator in Java is __________.


A. <>
B. !=
C. ==
D. ^=

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.

3.4 What is 1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 == 0.5?


A. true
B. false
C. There is no guarantee that 1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 == 0.5 is true.

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

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);
D. if (radius <= 0) [Link](radius * radius * 3.14159);

[Link]
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

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 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

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

[Link]
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.

3.11 Analyze the following code:


boolean even = false;
if (even = true) {
[Link]("It is even");
}
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.

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)

3.13 Analyze the following code.


boolean even = false;
if (even) {
[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).

[Link]
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.

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

3.16 What is the output from [Link]((int)[Link]() * 4)?


A. 0
B. 1
C. 2
D. 3
E. 4
3.17 What is the possible output from [Link]((int)([Link]() * 4))?
A. 0
B. 1
C. 2
D. 3
E. 4

[Link]
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:
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

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]
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

Case Study: Computing Taxes


3.20 The __________ method immediately terminates the program.
A. [Link](0);
B. [Link](0);
C. [Link](0);
D. [Link](0);
E. [Link](0);

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)

[Link]
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)
D. (1 > x > 100) || (x < 0)

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

3.24 Assume x = 4, which of the following is true?


A. !(x == 4)
B. x != 4
C. x == 5
D. x != 5

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

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

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

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

[Link]
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

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

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

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

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.

3.34 Which of the following are so called short-circuit operators?


A. &&
B. &
C. ||
D. |

[Link]
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

3.36 Analyze the following program fragment:


int x;
double d = 1.5;

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.

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

[Link]
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.

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

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. ^, ||, &&, *, +

[Link]
3.41 What is y displayed in the following code?
public class Test1 {
public static void main(String[] args) {
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.

3.42 Which of the following operators are right-associative.


A. *
B. + (binary +)
C. %
D. &&
E. =

3.43 What is the value of the following expression?


true || true && false
A. true
B. false

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)

[Link]
Mathematical Functions, Characters, and Strings
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))

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)

4.3 [Link](0.5) returns _______.


A. 30
B. [Link](30)
C. [Link] / 4
D. [Link] / 2

4.4 [Link]([Link]) returns _______.


A. 0.0
B. 1.0
C. 0.5
D. 0.4

4.5 [Link]([Link]) returns _______.


A. 0.0
B. 1.0
C. -1.0
D. 0.5

The Rounding Methods


4.6 What is [Link](3.6)?
A. 3.0
B. 3
C. 4
D. 4.0

4.7 What is [Link](3.6)?


A. 3.0
B. 3

[Link]
C. 4.0
D. 5.0

4.8 What is [Link](3.5)?


A. 3.0
B. 3
C. 4
D. 4.0
E. 5.0

4.9 What is [Link](3.6)?


A. 3.0
B. 3
C. 4.0
D. 5.0

4.10 What is [Link](3.6)?


A. 3.0
B. 3
C. 4
D. 5.0

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'

4.12 A Java character is stored in __________.


A. one byte
B. two bytes
C. three bytes
D. four bytes

4.13 The Unicode of 'a' is 97. What is the Unicode for 'c'?
A. 96
B. 97
C. 98
D. 99

Escape Sequences for Special Characters


4.14 Which of the following statement prints smith\exam1\[Link]?

[Link]
A. [Link]("smith\exam1\[Link]");
B. [Link]("smith\\exam1\\[Link]");
C. [Link]("smith\"exam1\"[Link]");
D. [Link]("smith"\exam1"\[Link]");

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
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 + " ");

4.17 Will [Link]((char)4) display 4?


A. Yes
B. No

4.18 What is the output of [Link]('z' - 'a')?


A. 25
B. 26
C. a
D. z

4.19 An int variable can hold __________.


A. 'x'
B. 120
C. 120.0
D. "x"
E. "120"

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";
4.21 '3' - '2' + 'm' / 'n' is ______.
A. 0
B. 1

[Link]
C. 2
D. 3

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')

4.23 Which of the following is not a correct method in the Character class?
A. isLetterOrDigit(char)
B. isLetter(char)
C. isDigit()
D. toLowerCase(char)
E. toUpperCase()

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")

Getting 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.

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

4.27 Note that the Unicode for character A is 65. The expression "A" + 1 evaluates to
________.

[Link]
A. 66
B. B
C. A1
D. Illegal expression

4.28 Note that the Unicode for character A is 65. The expression 'A' + 1 evaluates to
________.
A. 66
B. B
C. A1
D. Illegal expression

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")

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]());

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
4.32 "abc".compareTo("aba") returns ___________.
A. 1
B. 2
C. -1
D. -2
E. 0

4.33 "AbA".compareToIgnoreCase("abC") returns ___________.


A. 1
B. 2

[Link]
C. -1
D. -2
E. 0

4.34 ____________________ returns true.


A. "peter".compareToIgnoreCase("Peter")
B. "peter".compareToIgnoreCase("peter")
C. "peter".equalsIgnoreCase("Peter")
D. "peter".equalsIgnoreCase("peter")
E. "peter".equals("peter")
Obtaining Substrings

4.35 What is the return value of "SELECT".substring(0, 5)?


A. "SELECT"
B. "SELEC"
C. "SELE"
D. "ELECT"

4.36 What is the return value of "SELECT".substring(4, 4)?


A. an empty string
B. C
C. T
D. E

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') ...

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]
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);

4.40 The __________ method parses a string s to a double value.


A. [Link](s);
B. [Link](s);
C. [Link](s);
D. [Link](s);

Formatting Console Output


4.41 Which of the following are valid specifiers for the printf statement?
A. %4c
B. %10b
C. %6d
D. %8.2d
E. %10.2e
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
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
4.44 The statement [Link]("%5d", 123456) outputs ___________.
A. 12345
B. 23456
C. 123456
D. 12345.6
4.45 The statement [Link]("%10s", 123456) outputs ___________. (Note: *
represents a space)
A. 123456****
B. 23456*****
C. 12345*****
D. ****123456
4.46 Analyze the following code:

[Link]
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 for double value. The
code has an error.

[Link]
Loops
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

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

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
5.4 What is the output of the following code?

int x = 0;

[Link]
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

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

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
E. 0

[Link]
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

5.8 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

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

The for Loop


5.10 Analyze the following statement:
double sum = 0;
for (double d = 0; d < 10;) {
d += 0.1;
sum += sum + d;
}

[Link]
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.

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:
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

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]("Sum is " + sum);
C:
double sum = 0;

[Link]
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

5.13 The following loop displays _______________.


for (int i = 1; i <= 10; i++) {
[Link](i + " ");
i++;
}
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

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

[Link]
5.15 What is the output for y?
int y = 0;
for (int i = 0; i < 10; ++i) {
y += i;
}
[Link](y);
A. 10
B. 11
C. 12
D. 13
E. 45

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

5.17 Is the following loop correct?


for ( ; ; );
A. Yes
B. No

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

[Link]
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.
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);

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

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]();
}
Pattern A Pattern B Pattern C Pattern D
1 123456 1 123456
12 12345 21 12345
123 1234 321 1234
1234 123 4321 123
12345 12 54321 12
123456 1 654321 1
A. Pattern A
B. Pattern B
C. Pattern C
D. Pattern D

[Link]
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

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.

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.

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

[Link]
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

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

5.28 What is the output after the following loop terminates?


int number = 25;
int i;
boolean isPrime = true;
for (i = 2; i < number && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
[Link]("i is " + i + " isPrime is " + isPrime);
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

[Link]
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]("i is " + i + " isPrime is " + isPrime);
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

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

5.31 Will the following program terminate?


int balance = 10;
while (true) {
if (balance < 9)
continue;
balance = balance - 9;
}
A. Yes
B. No

[Link]
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
C. 1
D. 2
E. The loop does not end

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

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

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

[Link]
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];
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

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]();
}
}
}

[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.

[Link]
Methods
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

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
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)

Calling a Method
6.4 Arguments to methods always appear within __________.
A. brackets
B. parentheses
C. curly braces
D. quotation marks

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
6.6 Does the method call in the following method cause compile errors?
public static void main(String[] args) {
[Link](2, 4);
}

[Link]
A. Yes
B. No

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

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 100.
D. Write a method that converts an uppercase letter to lowercase.

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');
}
}
}

[Link]
A. int
B. double
C. boolean
D. char
E. void

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

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);

[Link]
C. [Link]("number");
D. return number;

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
D. pass by name

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

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;
nPrint("A message", k);
A. 0
B. 1
C. 2
D. 3

[Link]
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.
D. The program does not compile because the compiler cannot distinguish which
xmethod to invoke.

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.

[Link]
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)" 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.

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);
}
}

[Link]
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.
D. The program runs and prints 2 twice.

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

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

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

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'

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'

[Link]
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)

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

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
D. Stepwise refinement

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

[Link]
Single-Dimensional Arrays
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)

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
C. 3.5
D. 5.5
E. undefined

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];

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

[Link]
7.5 How many elements are in array double[] list = new double[5]?
A. 4
B. 5
C. 6
D. 0

7.6 What is the correct term for numbers[99]?


A. index
B. index variable
C. indexed variable
D. array variable
E. array

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

7.8 Analyze the following code.


public class Test {
public static void main(String[] args) {
int[] x = new int[3];
[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.

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'};

[Link]
7.10 How can you initialize an array of two characters to 'a' and 'b'?
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'};

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};
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.

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

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](indexOfMax);
A. 0
B. 1
C. 2

[Link]
D. 3
E. 4

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.

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.

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 + " ");
A. 1 2 3 4 5 6
B. 6 1 2 3 4 5

[Link]
C. 6 2 3 4 5 1
D. 1 1 2 3 4 5
E. 2 3 4 5 6 1

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.

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]; 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

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"};

[Link]
Copying Arrays

7.20 In the following code, what is the output for list2?


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

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] + " ");
}
}
A. 1 2 3
B. 1 1 1
C. 0 1 2
D. 0 1 3

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];

[Link]
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

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](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

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] + " ");
}
}

[Link]
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.

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.

7.26 Analyze the following code:

public class Test {


public static void main(String[] args) {
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.

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]);
D. [Link](sourceArray, 0, targetArray, 0, [Link]);

[Link]
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

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]++;
}

public static void increase(int y) {


y++;
}
}
A. 0 0
B. 1 1
C. 2 2
D. 2 1
E. 1 2

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);

[Link]
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 - 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

7.31 Analyze the following code:

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] + " ");

[Link]
}

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.

7.32 Analyze the following code:

public class Test1 {


public static void main(String[] args) {
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.

[Link]
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
D. dynamic memory

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

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};

7.36 The reverse method is defined in the textbook. What is list1 after executing the
following statements?

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

[Link]
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

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)
E. public static void print(int n, double... numbers)

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});

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
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

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

[Link]
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

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

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)

7.45 Assume int[] scores = {1, 20, 30, 40, 50}, what value does
[Link](scores, 30) return?
A. 0
B. -1
C. 1
D. 2
E. -2

[Link]
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

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]

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]

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

[Link]
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 ++;

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);

7.52 Analyze the following code:

public class Test {


public static void main(String argv[]) {
[Link]("[Link] is " + [Link]);
}
}
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.

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[])
C. public static void main(String[] x)
D. public static void main(String x[])
E. static void main(String[] args)

[Link]
Multidimensional Arrays
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'}};

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

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]

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

8.5 How many elements are in array matrix (int[][] matrix = new int[5][5])?
A. 14
B. 20
C. 25
D. 30

[Link]
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.

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

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

[Link]
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 < 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

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
E. 33

[Link]
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

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

[Link]
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] + " ");
}
}
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

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}};

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, 6, 1, 2}};

for (int row = 0; row < [Link]; row++) {


[Link](m(values[row]) + " ");
}
}

[Link]
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

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

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'}}};

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]);
}
}

[Link]
A. 1
B. 2
C. 4
D. 5
E. 6

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

[Link]
Objects and Classes

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

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

9.3 An object is an instance of a __________.


A. program
B. class
C. method
D. data

9.4 The keyword __________ is required to declare a class.


A. public
B. private
C. class
D. All of the above.

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

[Link]
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.

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.
D. Constructors are invoked using the new operator when an object is created.

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]
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.

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.

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);
}
}

[Link]
A. The program has a compile error because test is not 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.

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

9.13 Which of the following statements are true?


A. Local variables do not have default values.
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.

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.
D. The program compiles and runs fine.

[Link]
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.

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.

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.

[Link]
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

9.19 Which of the following statements are correct?


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.

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))

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

[Link]
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

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

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;

9.25 Analyze the following code.

public class Test {


public static void main(String[] args) {
int n = 2;
xMethod(n);

[Link]("n is " + n);


}

void xMethod(int n) {
n++;

[Link]
}
}
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.

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);
}

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

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);

[Link]
Foo f3 = new Foo();
[Link]("f3.i is " + f3.i + " f3.s is " + f3.s);
}

public Foo() {
i++;
s++;
}
}
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

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]()

9.29 Suppose the xMethod() is invoked in the following constructor in a class,


xMethod() is _________ in the class.

public MyClass() {
xMethod();
}
A. a static method
B. an instance method
C. a static method or an instance method

[Link]
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

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.
D. use the static modifier on the constructor.

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.

[Link]
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.

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);
}
}
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.

Data Field Encapsulation


9.35 Which of the following statements are true?
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.

[Link]
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()

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 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.

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

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] = " + [Link]);
[Link]("times = "+ times);
}

public static void increment(Count c, int times) {


[Link]++;
times++;
}
}

[Link]
class Count {
int count;

Count(int c) {
count = c;
}

Count() {
count = 1;
}
}

A. 101
B. 100
C. 99
D. 98

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](
"[Link] = " + [Link]);
[Link]("times = "+ times);
}

public static void increment(Count c, int times) {


[Link]++;
times++;
}
}

class Count {
int count;

Count(int c) {
count = c;
}

[Link]
Count() {
count = 1;
}
}
A. 101
B. 100
C. 99
D. 98
E. 0

9.41 What is the output of the following program?

import [Link];

public class Test {


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

[Link]
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.
D. x contains a reference to an array and each element in the array can hold a Circle
object.

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.

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.
D. A readable object type property in an immutable object must also be immutable.
E. An immutable object contains no mutator methods.

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);

[Link]
}
}
A. i + j is 5
B. i + j is 6
C. i + j is 22
D. i + j is 23

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

9.47 What is the output for the third 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);
}

[Link]
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

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

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.

9.50 Analyze the following code:

class Test {
private double i;

public Test(double i) {
this.t();
this.i = i;
}

[Link]
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).

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]

Common questions

Powered by AI

Incorrect initialization of loop variables can drastically alter a loop's behavior, potentially causing it to execute zero times, run indefinitely, or produce incorrect outputs. For instance, initializations that exceed or never meet the loop's terminating condition bypass the loop entirely or create infinite iterations .

In Java, a class serves as a blueprint for creating objects, encapsulating data for the object and methods to manipulate that data. This modeling of real-world entities enables object-oriented programming by allowing code reuse, scalability, and easier maintenance .

Java handles arrays by allocating fixed memory for defined element types and sizes upon initialization, allowing accessed elements through index positions. Common pitfalls include ArrayIndexOutOfBoundsException, especially if loops attempt to access beyond the defined bounds. In the example 'for (int i = 0; i < x.length; i++) x[i] = i;', accessing 'x[i]' after looping leads to such an error .

In Java, a semicolon immediately after the for loop declaration, such as 'for (i = 0; i < 10; i++);', creates an empty loop body where no operations are performed each iteration. This results in a loop that merely increments the iterator without executing any meaningful code, so only statements after it are executed once the loop exits. In this case, 'System.out.println(i + 4);' prints '14', because the loop completed after incrementing 'i' to 10 .

The loop structure, including both the increment strategy and order of computation, significantly impacts numeric precision. In computing series such as '1/2 + 2/3 + ...', changes to the iteration order or calculation can reduce rounding errors. Adding from smallest to largest generally maintains greater precision due to less accumulation of round-off errors .

Constructors in Java initialize objects of a class, serving as special methods sharing the class name but without a return type. They are invoked using the 'new' keyword to allocate memory and configure attributes. Constructors support parameterization for customized initialization and can be overloaded to provide multiple ways to instantiate the class .

Floating-point arithmetic inaccuracies can result in loop conditions not terminating as expected. For example, in the code fragment involving 'double d = 0; while (d != 10.0)', the increment 'd += 0.1' suffers from precision errors, causing 'd' to never exactly reach 10.0, which may lead to an infinite loop .

The choice between prefix (e.g., '++count') and postfix (e.g., 'count++') increment determines when the increment occurs relative to the loop's condition check. A do-while loop checks the condition post execution of the loop body. Using postfix increment, the condition is checked with the current loop counter and the increment happens afterward, effectively running an additional iteration than when prefix increment is used .

The structure of nested loops causes the inner loops to complete all their iterations for each iteration of the outer loop. For instance, in a nested loop where the outer loop runs 'n' times and the inner loop runs 'm' times per outer iteration, the statement inside the inner loop runs 'n * m' times. In the example with 'for (int i = 0; i < 10; i++) for (int j = 0; j < i; j++)', the inner loop is controlled by 'i', resulting in a total of 45 executions .

Using a floating-point type as a loop control variable can introduce precision-related issues due to how floating-point arithmetic works. For example, in a typical use case involving incremental operations (e.g., 'd += 0.1'), the expected condition check ('d < 10') might never be met due to round-off errors. This could result in infinite loops or loops exiting prematurely .

You might also like