Java Programming Fundamentals
- 101Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is the primary purpose of the Java Development Kit (JDK)?
What is the primary purpose of the Java Development Kit (JDK)?
101 questions
- 1
What is the primary purpose of the Java Development Kit (JDK)?
- A
To provide only a graphical interface for running Java applications
- B
To organize Java classes into packages automatically
- C
To provide tools and software needed to develop Java applications
- D
To convert Java source code directly into processor-specific code without a runtime
Correct answer
CTo provide tools and software needed to develop Java applications
Explanation
The JDK is a software development environment that includes the Java compiler, reusable code, a runtime environment, and other development tools.
- A
- 2
Which statement correctly describes the Java compiler’s role when a Java program is built?
- A
It converts Java source code into Java bytecode
- B
It converts Java bytecode into source code for the operating system
- C
It runs the program’s main method while checking syntax
- D
It converts Java source code directly into operating-system native code
Correct answer
AIt converts Java source code into Java bytecode
Explanation
The Java compiler compiles source files into bytecode, which is stored in class files.
- A
- 3
What does the Java Virtual Machine (JVM) do when a Java program runs?
- A
It converts Java source files into bytecode during editing
- B
It translates native operating-system code into Java source code
- C
It organizes compiled classes into packages
- D
It translates Java bytecode into native code for the underlying operating system
Correct answer
DIt translates Java bytecode into native code for the underlying operating system
Explanation
The JVM loads bytecode and translates it into native code that the underlying operating system can execute.
- A
- 4
Why can the same Java bytecode run on different operating systems?
- A
The operating system ignores the bytecode and runs the original source file
- B
Java source code is rewritten by the compiler for every operating system automatically
- C
Java bytecode contains separate native programs for every operating system
- D
Each operating system with a Java runtime can use its JVM to translate the bytecode
Correct answer
DEach operating system with a Java runtime can use its JVM to translate the bytecode
Explanation
Bytecode is platform independent; a Java runtime environment on each platform provides a JVM to translate it for that operating system.
- A
- 5
Which pairing correctly describes the relationship between a Java Runtime Environment (JRE) and a JVM?
- A
The JRE includes a JVM that runs Java bytecode
- B
The JRE is a source-code editor, and the JVM is its compiler
- C
The JRE stores source files, and the JVM organizes them into packages
- D
The JVM includes a JRE that compiles Java source code
Correct answer
AThe JRE includes a JVM that runs Java bytecode
Explanation
The JRE includes the JVM, which is the component that runs Java bytecode.
- A
- 6
What is a command-line application, as contrasted with a graphical user-interface application?
- A
It must be written in a language other than Java
- B
It can be run from a command line and does not provide a graphical user interface
- C
It cannot accept input from a user
- D
It can only be run inside a code editor and must provide a graphical interface
Correct answer
BIt can be run from a command line and does not provide a graphical user interface
Explanation
A command-line application runs from a command line and does not have a graphical user interface.
- A
- 7
What is the purpose of a Java package in a project?
- A
To specify which code editor the project uses
- B
To translate bytecode into native code
- C
To group related classes and provide a namespace for them
- D
To store the values of primitive variables while a program runs
Correct answer
CTo group related classes and provide a namespace for them
Explanation
Packages group related classes and provide namespaces, which helps organize projects that may contain many classes.
- A
- 8
Why might a project use a reversed company domain as its base package name?
- A
It tells the compiler which operating system to target
- B
It names the JVM that will execute the program
- C
It creates a distinctive namespace for the project’s classes
- D
It determines the data types available in the project
Correct answer
CIt creates a distinctive namespace for the project’s classes
Explanation
Using a reversed domain is a convention for creating a namespace that helps distinguish a project’s classes; an actually registered domain is not required.
- A
- 9
Which statement about a Java source file is correct?
- A
A Java source file uses the
.classextension - B
A Java source file contains only bytecode, not source code
- C
A Java source file uses the
.javaextension - D
A Java source file must have the same name as its package
Correct answer
CA Java source file uses the
.javaextensionExplanation
Java source files use the
.javaextension; compiled bytecode is commonly stored in.classfiles. - A
- 10
Which statement correctly distinguishes Java SE from Java EE in the described Java editions?
- A
Java SE is the core platform, while Java EE adds libraries for large-scale and distributed systems
- B
Java SE is built on Java EE and provides extra libraries for smart cards
- C
Java SE is only a code editor, while Java EE is the Java compiler
- D
Java SE is a subset for smart cards, while Java EE is designed for mobile devices
Correct answer
AJava SE is the core platform, while Java EE adds libraries for large-scale and distributed systems
Explanation
Java Standard Edition is the core Java platform; Java Enterprise Edition builds on it and adds libraries for large-scale, distributed, multi-tier software.
- A
- 11
In Java, what is a function that belongs to a class called?
- A
A field
- B
A package
- C
A method
- D
A parameter
Correct answer
CA method
Explanation
A function that is part of a class is referred to as a method.
- A
- 12
What is the role of a class in a Java program?
- A
It acts as a container for related methods and other members
- B
It translates source code into bytecode
- C
It stores only one primitive value
- D
It acts as a value passed into a method
Correct answer
AIt acts as a container for related methods and other members
Explanation
A class organizes related code by serving as a container for methods and other members.
- A
- 13
What is the role of the
mainmethod in a Java program?- A
It is required to return a string to the operating system
- B
It is the package that contains every Java class
- C
It is the method that compiles all source files
- D
It is the program’s entry point when the program is run
Correct answer
DIt is the program’s entry point when the program is run
Explanation
When a Java program is executed, its
mainmethod is called as the entry point. - A
- 14
What does the
voidreturn type indicate for a method?- A
The method can return any primitive value
- B
The method does not return a value
- C
The method is not allowed to contain statements
- D
The method is available only inside its own class
Correct answer
BThe method does not return a value
Explanation
voidspecifies that a method does not return a value. - A
- 15
What is the purpose of a method parameter?
- A
It marks the end of a Java statement
- B
It determines which package contains the method
- C
It provides a named input through which a value can be passed to a method
- D
It specifies the value returned by the method
Correct answer
CIt provides a named input through which a value can be passed to a method
Explanation
Parameters are the named inputs declared in a method; callers supply values, called arguments, for those inputs.
- A
- 16
What is the purpose of an access modifier such as
public?- A
It controls whether other classes or methods can access a declaration
- B
It specifies whether a method returns a value
- C
It determines whether a class is compiled into bytecode
- D
It indicates that a variable is a constant
Correct answer
AIt controls whether other classes or methods can access a declaration
Explanation
Access modifiers, including
publicandprivate, control the accessibility of classes and members. - A
- 17
Which naming convention is used for Java class names in the described conventions?
- A
Camel case, with only the first word beginning with an uppercase letter
- B
All lowercase letters with words separated by underscores
- C
All uppercase letters with words separated by spaces
- D
Pascal case, with each word beginning with an uppercase letter
Correct answer
DPascal case, with each word beginning with an uppercase letter
Explanation
Class names use Pascal naming convention, in which the first letter of every word is uppercase.
- A
- 18
Which naming convention is used for Java method names in the described conventions?
- A
Camel case, with the first word lowercase and later words capitalized
- B
All uppercase letters with words separated by underscores
- C
All lowercase letters with no distinction between words
- D
Pascal case, with every word beginning with an uppercase letter
Correct answer
ACamel case, with the first word lowercase and later words capitalized
Explanation
Method names use camel case: the first word begins with a lowercase letter and each later word begins with an uppercase letter.
- A
- 19
What does a semicolon normally indicate in Java?
- A
The end of a package name
- B
The beginning of a class
- C
The start of a comment
- D
The end of a statement
Correct answer
DThe end of a statement
Explanation
Java statements are terminated with semicolons.
- A
- 20
What is the effect of prefixing Java code with
//?- A
It declares a method that returns no value
- B
It makes the following text a string literal
- C
It imports a class from another package
- D
It marks the following text on that line as a comment, not executable code
Correct answer
DIt marks the following text on that line as a comment, not executable code
Explanation
A double slash begins a single-line comment; comments explain code and are not executed.
- A
- 21
Which statement correctly compares primitive and reference types in Java?
- A
Primitive variables hold object addresses, while reference variables hold only simple values
- B
Both categories must be initialized using the
newoperator - C
Both categories always store their values directly in the variable
- D
Primitive variables hold simple values, while reference variables hold references to objects
Correct answer
DPrimitive variables hold simple values, while reference variables hold references to objects
Explanation
Primitive types are used for simple values; reference types refer to more complex objects.
- A
- 22
Which primitive type is designed to store a single character?
- A
double - B
String - C
boolean - D
char
Correct answer
DcharExplanation
The primitive type
charstores a single character;Stringis a reference type for sequences of characters. - A
- 23
Which primitive type stores either
trueorfalse?- A
char - B
boolean - C
String - D
int
Correct answer
BbooleanExplanation
A
booleanstores one of two values:trueorfalse. - A
- 24
Which statement correctly describes
floatanddoublein the lesson’s comparison of primitive types?- A
Both store numbers with decimal points, and
doubleuses more memory thanfloat - B
floatis a reference type, whiledoubleis a primitive type - C
Both store whole numbers, and
floatuses more memory thandouble - D
floatstores characters, whiledoublestores boolean values
Correct answer
ABoth store numbers with decimal points, and
doubleuses more memory thanfloatExplanation
floatanddoublerepresent floating-point numbers;floattakes four bytes anddoubletakes eight bytes. - A
- 25
Why might a program use a
byterather than anintto store a person’s age?- A
A
byteis a reference type that stores objects more efficiently - B
An
intcannot store whole numbers - C
A
bytecan store decimal values, while anintcannot - D
A
bytecan represent the small range needed for an age while using less memory
Correct answer
DA
bytecan represent the small range needed for an age while using less memoryExplanation
The described
byterange is sufficient for ordinary ages, and it uses less memory than anint. - A
- 26
Why does a large integer literal assigned to a
longsometimes need anLsuffix?- A
The suffix converts a string containing digits into a
long - B
Integer literals are treated as
intby default, so the suffix marks the literal as along - C
The suffix allocates additional memory for the variable at runtime
- D
The suffix tells Java to treat the literal as a
float
Correct answer
BInteger literals are treated as
intby default, so the suffix marks the literal as alongExplanation
Java treats integer literals as
intby default; anLsuffix marks a literal as alongwhen it exceeds theintrange. - A
- 27
Why does a decimal literal assigned to a
floatneed anFsuffix in the described example?- A
Decimal literals are treated as strings by default, and
Fconverts them to numbers - B
The suffix marks the variable as a constant
- C
Decimal literals are treated as
doubleby default, andFmarks the literal as afloat - D
The suffix tells Java to round the value to a whole number
Correct answer
CDecimal literals are treated as
doubleby default, andFmarks the literal as afloatExplanation
A decimal literal is treated as a
doubleby default, so anFsuffix is used to represent it as afloat. - A
- 28
What happens when one primitive variable is assigned to another primitive variable of the same type?
- A
The value is copied, so later changes to one variable do not change the other
- B
The variables are merged into a single memory location
- C
The assignment is rejected because primitive values cannot be copied
- D
Both variables become references to one shared object
Correct answer
AThe value is copied, so later changes to one variable do not change the other
Explanation
Primitive values are copied by value; the two variables remain independent.
- A
- 29
What happens when a reference variable is assigned to another reference variable?
- A
The reference variable takes ownership of the class definition
- B
The reference is copied, so both variables can refer to the same object
- C
The assignment converts the object into a primitive value
- D
The object is automatically duplicated into a separate object
Correct answer
BThe reference is copied, so both variables can refer to the same object
Explanation
Reference types are copied by reference. The variables can refer to the same object, so changes through one reference can be observed through the other.
- A
- 30
What does the
newoperator do when creating an ordinary object such as aDate?- A
It releases memory used by an existing object
- B
It imports the class from its package
- C
It allocates memory for an object and creates an instance of its class
- D
It converts the class into a primitive type
Correct answer
CIt allocates memory for an object and creates an instance of its class
Explanation
The
newoperator is used to create an object instance and allocate memory for it; the runtime manages object memory afterward. - A
- 31
What is an object in relation to a class?
- A
A method parameter with no assigned value
- B
An instance created from the class’s definition or blueprint
- C
A primitive value used to define the class
- D
A package that contains the class’s methods
Correct answer
BAn instance created from the class’s definition or blueprint
Explanation
A class defines a template or blueprint; an object is an instance of that class.
- A
- 32
Why can code use a class from another package only after importing it, unless it is automatically available?
- A
The import converts the class into a primitive type
- B
The import changes the class’s access modifier to
public - C
The import compiles the class into the main method
- D
The import makes the class from that package available by its simple name
Correct answer
DThe import makes the class from that package available by its simple name
Explanation
An import allows code to refer to a class from another package without writing its full package name;
java.langis automatically available. - A
- 33
Why can a Java string be initialized from a string literal without using
new?- A
The
newoperator cannot create string objects - B
The literal is stored as a
charvariable instead - C
It is a convenient shorthand, even though
Stringremains a reference type - D
String literals make
Stringa primitive type
Correct answer
CIt is a convenient shorthand, even though
Stringremains a reference typeExplanation
Java provides a shorter way to create strings using literals, but strings are still reference types.
- A
- 34
What does concatenating two strings with
+do?- A
It changes the original strings in place
- B
It converts both strings into character arrays
- C
It joins their text into a new string
- D
It compares the strings by their memory addresses
Correct answer
CIt joins their text into a new string
Explanation
The
+operator concatenates, or joins, strings to produce combined text. - A
- 35
What does the
length()method return for a string?- A
The memory address of the string
- B
The number of characters in the string
- C
The index of the first character
- D
The number of words in the string
Correct answer
BThe number of characters in the string
Explanation
length()returns the number of characters in a string. - A
- 36
What does
indexOfreturn when the requested character or text does not occur in a string?- A
0 - B
The string’s length
- C
A boolean value of
false - D
-1
Correct answer
D-1Explanation
The described
indexOfbehavior is to return-1when the searched-for content is not found. - A
- 37
What does the
replacemethod do to the original string?- A
It returns a new string with the requested replacements; the original remains unchanged
- B
It returns the index of the first character that was replaced
- C
It deletes the original string and stores the replacement in its place
- D
It modifies the original string directly and returns no value
Correct answer
AIt returns a new string with the requested replacements; the original remains unchanged
Explanation
Strings are immutable in Java, so
replacereturns a new string instead of modifying the original. - A
- 38
What does calling
toLowerCase()on a string produce?- A
A boolean indicating whether the string was lowercase
- B
A changed version of the original string stored in the same object
- C
A new string with its characters converted to lowercase
- D
The number of lowercase characters in the string
Correct answer
CA new string with its characters converted to lowercase
Explanation
toLowerCase()returns a new string; it does not mutate the original string. - A
- 39
What is the purpose of the
trim()method?- A
To remove every space between words in a string
- B
To shorten a string to its first character
- C
To remove leading and trailing whitespace from a string
- D
To convert all characters to uppercase
Correct answer
CTo remove leading and trailing whitespace from a string
Explanation
trim()removes extra whitespace at the beginning and end of a string. - A
- 40
How can two string values be compared for equal text using the methods described?
- A
Use
=between the strings - B
Call
equalson one string and pass the other string - C
Call
lengthon both strings and compare the results - D
Use
==to guarantee their text is compared
Correct answer
BCall
equalson one string and pass the other stringExplanation
The
equalsmethod compares string values. The equality operator on references compares references, not necessarily their text. - A
- 41
Why may
next()fail to read a user’s full name containing a space?- A
It reads a single token, so text after the space remains unread
- B
It reads only numeric input
- C
It converts the input to lowercase automatically
- D
It removes all characters after the first letter
Correct answer
AIt reads a single token, so text after the space remains unread
Explanation
next()reads one token; whitespace separates tokens, so a name with spaces requires more than one token-reading call or a line-reading method. - A
- 42
Which escape sequence inserts a new line within a Java string?
- A
\n - B
`\
- C
\\ - D
\t
Correct answer
A\nExplanation
The escape sequence
\ninserts a new line.\tinserts a tab,\\represents a backslash, and\"represents a double quote inside a string. - A
- 43
Why must a backslash in a string be escaped when representing a Windows path?
- A
A backslash converts the string to a file object
- B
A backslash marks the end of a string, so it must be doubled to close the string
- C
A backslash begins escape sequences, so a literal backslash is written as
\\ - D
A backslash is treated as a comment marker inside strings
Correct answer
CA backslash begins escape sequences, so a literal backslash is written as
\\Explanation
Backslash introduces escape sequences in Java strings;
\\in source represents one literal backslash in the resulting string. - A
- 44
How is an array’s first element accessed in Java?
- A
Using index
0 - B
Using index equal to the array’s length
- C
Using index
1 - D
Using the array’s
firstfield
Correct answer
AUsing index
0Explanation
Java arrays are zero-indexed, so the first element is at index
0. - A
- 45
What happens when a program accesses an array index outside its valid range?
- A
An exception is raised and the program may terminate
- B
The value is silently stored in the next available position
- C
Java automatically expands the array to include the index
- D
The invalid index is treated as the last valid index
Correct answer
AAn exception is raised and the program may terminate
Explanation
Accessing an index outside an array’s bounds raises an exception, which can cause the program to crash if not handled.
- A
- 46
How can a program obtain a readable string representation of a one-dimensional primitive array?
- A
Use
Arrays.deepToStringonly - B
Call
lengthon the array and print that value - C
Print the array variable directly
- D
Use the appropriate overloaded
Arrays.toStringmethod
Correct answer
DUse the appropriate overloaded
Arrays.toStringmethodExplanation
The overloaded
Arrays.toStringmethods produce a readable representation of one-dimensional arrays. - A
- 47
What is the default value of an unassigned element in an integer array?
- A
0 - B
An empty string
- C
null - D
An unspecified random value
Correct answer
A0Explanation
Integer array elements are initialized to
0by default; boolean elements default tofalse. - A
- 48
What is an important limitation of Java arrays after they are created?
- A
Their elements cannot be read by index
- B
They can contain only primitive values
- C
Their length is fixed
- D
They cannot be sorted
Correct answer
CTheir length is fixed
Explanation
A Java array has a fixed length after creation. Collections are used when a resizable structure is needed.
- A
- 49
Which method sorts an array using the
Arraysclass?- A
array.length() - B
Arrays.order(array) - C
Arrays.toString(array) - D
Arrays.sort(array)
Correct answer
DArrays.sort(array)Explanation
The
sortmethod of theArraysclass sorts an array. - A
- 50
How does a two-dimensional array differ from a one-dimensional array?
- A
It has two indices, such as a row index and a column index
- B
It must contain exactly two arrays
- C
It stores only two values total
- D
It can contain only numeric data
Correct answer
AIt has two indices, such as a row index and a column index
Explanation
A two-dimensional array uses two indices to identify an element, commonly representing a row and a column.
- A
- 51
Which method is suited to producing a readable representation of a multidimensional array?
- A
String.length - B
Arrays.deepToString - C
Arrays.sort - D
Arrays.toString
Correct answer
BArrays.deepToStringExplanation
Arrays.deepToStringis used to display nested, multidimensional array contents;Arrays.toStringis for a single dimension. - A
- 52
What is the role of an array’s
lengthfield?- A
It reports the index of the final element
- B
It returns a string representation of the elements
- C
It reports the number of elements the array can hold
- D
It changes the array’s size
Correct answer
CIt reports the number of elements the array can hold
Explanation
An array’s
lengthfield gives its number of elements; the last valid index is one less than that length. - A
- 53
Which statement about Java array initialization is correct when the elements are already known?
- A
An array must always be filled by assigning each index in a separate statement
- B
An array can be initialized with its elements inside curly braces
- C
An array can be initialized only using
Arrays.toString - D
An array must be declared as a collection to list its initial elements
Correct answer
BAn array can be initialized with its elements inside curly braces
Explanation
When the elements are known, Java permits a concise array initializer using curly braces and comma-separated values.
- A
- 54
What does the modulus operator
%return?- A
The product of two values
- B
The absolute value of a number
- C
The quotient of a division
- D
The remainder of a division
Correct answer
DThe remainder of a division
Explanation
The modulus operator returns the remainder; it can be used to test whether a number is divisible by another number.
- A
- 55
Why does integer division of two whole numbers produce a whole-number result in Java?
- A
An integer variable cannot hold the quotient, so Java returns zero
- B
Java automatically rounds every quotient upward
- C
The division operator returns a string for whole-number operands
- D
The operation uses integer arithmetic, which discards the fractional part
Correct answer
DThe operation uses integer arithmetic, which discards the fractional part
Explanation
When both operands are integers, integer division produces an integer result, so the fractional part is discarded.
- A
- 56
What is the result of evaluating
10 + 3 * 2under the usual Java arithmetic precedence?- A
26, because addition is evaluated before multiplication - B
15, because multiplication is ignored in an integer expression - C
32, because the operators are evaluated from left to right - D
16, because multiplication is evaluated before addition
Correct answer
D16, because multiplication is evaluated before additionExplanation
Multiplication has higher precedence than addition, so the expression is evaluated as 10+(3×2)=16.
- A
- 57
What is the purpose of parentheses in an arithmetic expression?
- A
They make every operator have equal precedence
- B
They convert a reference type into a primitive type
- C
They control evaluation order by grouping an expression
- D
They mark the expression as a comment
Correct answer
CThey control evaluation order by grouping an expression
Explanation
Parentheses have high precedence and can force a grouped expression to be evaluated before surrounding operations.
- A
- 58
How does postfix increment, as in
y = x++, differ from prefix increment, as iny = ++x?- A
Postfix assigns the old value to
ybefore incrementingx; prefix incrementsxbefore assigning toy - B
They always assign the same value to
yand leavexunchanged - C
Postfix increments
xtwice; prefix incrementsxonce - D
Postfix changes only
y; prefix changes onlyx
Correct answer
APostfix assigns the old value to
ybefore incrementingx; prefix incrementsxbefore assigning toyExplanation
With postfix increment, the expression yields the old value before incrementing. With prefix increment,
xis incremented first and the new value is yielded. - A
- 59
Which statement is equivalent to
x = x + 2?- A
x++ - B
x += 2 - C
x = 2 + x++ - D
x == 2
Correct answer
Bx += 2Explanation
The compound assignment
x += 2adds two toxand stores the result back inx. - A
- 60
When does implicit numeric casting generally occur in the described rules?
- A
Whenever converting a string to any numeric type
- B
Whenever a variable is declared as
final - C
Only when converting a larger type into a smaller type
- D
When converting to a compatible type that can represent the value without losing data
Correct answer
DWhen converting to a compatible type that can represent the value without losing data
Explanation
Implicit casting occurs when Java can safely convert a value to a compatible type without a risk of data loss, such as widening from
bytetoint. - A
- 61
Why does assigning a
doubleexpression to anintrequire explicit conversion?- A
The conversion can lose the digits after the decimal point
- B
Java does not allow numeric types to be converted
- C
A
doubleis a reference type and cannot be assigned - D
An
intuses more memory than adouble
Correct answer
AThe conversion can lose the digits after the decimal point
Explanation
Converting a floating-point value to an integer can discard its fractional part, so it requires an explicit cast when that loss is intended.
- A
- 62
Which approach converts a numeric string such as
"42"into an integer?- A
Assign the string directly to an
intvariable - B
Use
Integer.parseIntwith the string - C
Cast the string to
intwith(int) - D
Use
Math.roundon the string
Correct answer
BUse
Integer.parseIntwith the stringExplanation
Integer.parseIntparses a string containing an integer representation and returns anint; a cast cannot convert a string to a number. - A
- 63
What happens if a decimal string is passed to
Integer.parseInt?- A
The method returns the number of digits in the string
- B
Parsing fails because the string is not a valid integer representation
- C
The method automatically returns a
double - D
The decimal part is always rounded to the nearest integer
Correct answer
BParsing fails because the string is not a valid integer representation
Explanation
Integer.parseIntexpects an integer representation; a decimal value such as1.1causes a parsing exception. - A
- 64
What does
Math.ceilreturn for a positive non-integer value such as1.1?- A
The nearest integer, represented as a
long - B
A random integer greater than the value
- C
The smallest integer greater than or equal to the value, represented as a
double - D
The largest integer less than or equal to the value, represented as an
int
Correct answer
CThe smallest integer greater than or equal to the value, represented as a
doubleExplanation
Math.ceilrounds upward to the smallest integer greater than or equal to its argument; its result is adouble. - A
- 65
Which description correctly distinguishes
Math.floorfromMath.ceilfor a value such as1.1?- A
floorrounds to the nearest integer;ceilalways returns zero - B
Both methods always return the same result for non-integers
- C
floorreturns a random lower value;ceilreturns a random higher value - D
floorgives the largest integer no greater than the value;ceilgives the smallest integer no less than it
Correct answer
Dfloorgives the largest integer no greater than the value;ceilgives the smallest integer no less than itExplanation
For 1.1,
Math.floorgives 1.0 andMath.ceilgives 2.0; the two methods round in opposite directions. - A
- 66
What is the role of
Math.random()in the described examples?- A
It returns a floating-point value between
0and1, which can be scaled by multiplication - B
It returns the same fixed value every time the program runs
- C
It rounds an input number to the nearest integer
- D
It returns an integer between
1and100by default
Correct answer
AIt returns a floating-point value between
0and1, which can be scaled by multiplicationExplanation
Math.random()returns adoublein the range from 0 up to, but not including, 1; multiplying it by 100 scales the range to 0 through values below 100. - A
- 67
What is the purpose of obtaining a currency-specific
NumberFormatinstance?- A
It converts a currency string into a Java class
- B
It performs arithmetic on currency values without returning a result
- C
It guarantees that a numeric value has no decimal digits
- D
It formats a number as currency, including currency symbols and localized separators
Correct answer
DIt formats a number as currency, including currency symbols and localized separators
Explanation
A currency-specific
NumberFormatformats values as currency, such as adding a currency symbol and grouping digits. - A
- 68
Why can’t code instantiate the
NumberFormatclass directly withnewin the described example?- A
It is abstract, so a factory method such as
getCurrencyInstanceis used to obtain an instance - B
It is a package name rather than a class
- C
It is a primitive type, so it has no constructor
- D
It is automatically instantiated only when a number is printed
Correct answer
AIt is abstract, so a factory method such as
getCurrencyInstanceis used to obtain an instanceExplanation
An abstract class cannot be instantiated directly; a factory method such as
getCurrencyInstancereturns a suitableNumberFormatinstance. - A
- 69
What does a percent-specific
NumberFormatdo to a value of0.1?- A
It formats the value as
0.1% - B
It changes the stored numeric value to
10 - C
It converts the value to the integer
10 - D
It formats the value as
10%
Correct answer
DIt formats the value as
10%Explanation
Percent formatting displays a decimal proportion as a percentage, so 0.1 is formatted as 10%.
- A
- 70
What is method chaining?
- A
Using one method to compile another method
- B
Declaring multiple methods inside a package
- C
Calling the same method repeatedly without arguments
- D
Calling a method on the value returned by another method
Correct answer
DCalling a method on the value returned by another method
Explanation
Method chaining uses the return value of one method call as the receiver for a subsequent method call.
- A
- 71
What must be supplied to a
Scannerwhen reading from the terminal in the described example?- A
A
NumberFormatinstance - B
System.in - C
The name of the main class
- D
System.out
Correct answer
BSystem.inExplanation
System.inis the input stream supplied to aScannerto read data from the terminal. - A
- 72
What is the difference between
System.inandSystem.out?- A
System.inis used for input, whileSystem.outis used for output - B
System.incompiles code, whileSystem.outruns bytecode - C
System.inis a method, whileSystem.outis a package - D
System.instores strings, whileSystem.outstores arrays
Correct answer
ASystem.inis used for input, whileSystem.outis used for outputExplanation
System.inis the standard input stream;System.outis the standard output stream used for terminal output. - A
- 73
Why does
Scanner.next()usually return only the first part of an input such as a full name?- A
It rejects all text containing letters
- B
It reads one token, and whitespace separates tokens
- C
It reads only the first character of each line
- D
It automatically trims and deletes the second word
Correct answer
BIt reads one token, and whitespace separates tokens
Explanation
next()reads one token, with whitespace acting as a separator;nextLine()reads the entire line. - A
- 74
Why is
nextLine()appropriate for reading a full name with spaces?- A
It reads the entire line, including multiple whitespace-separated words
- B
It reads a line only when the input is numeric
- C
It automatically converts the name to a character array
- D
It reads only the first word but preserves its spaces
Correct answer
AIt reads the entire line, including multiple whitespace-separated words
Explanation
Unlike
next(),nextLine()reads the entire line entered by the user, including spaces between words. - A
- 75
Why is it generally preferable to create a
Scanneronce outside a repeated input loop?- A
It avoids repeatedly creating unnecessary scanner objects
- B
It changes the loop condition into a boolean
- C
It makes the input automatically validate itself
- D
It causes
nextLine()to read only one token
Correct answer
AIt avoids repeatedly creating unnecessary scanner objects
Explanation
Creating a new scanner on every iteration is unnecessary; reusing one avoids repeatedly creating objects.
- A
- 76
In a mortgage calculator, how is an annual interest rate expressed as a percentage converted to a monthly decimal rate?
- A
Subtract
12from the annual percentage and divide by100 - B
Multiply the annual percentage by
100and then by12 - C
Divide the annual percentage by
12and then multiply by100 - D
Divide the annual percentage by
100and then by12
Correct answer
DDivide the annual percentage by
100and then by12Explanation
First divide by 100 to convert a percentage to a decimal rate, then divide by 12 to obtain a monthly rate.
- A
- 77
If a mortgage payment is calculated over a term measured in years, how is the number of monthly payments obtained?
- A
Divide the number of years by
12 - B
Add
12to the number of years - C
Multiply the number of years by
100 - D
Multiply the number of years by
12
Correct answer
DMultiply the number of years by
12Explanation
There are 12 monthly payments per year, so the number of payments is the number of years multiplied by 12.
- A
- 78
Why should a mortgage calculator validate input values before calculating a payment?
- A
Validation makes the formula unnecessary
- B
Validation guarantees every user enters the same loan amount
- C
Invalid or nonnumeric input can cause incorrect behavior or a program error
- D
Invalid input is automatically converted to a valid value by Java
Correct answer
CInvalid or nonnumeric input can cause incorrect behavior or a program error
Explanation
Nonnumeric or out-of-range values can cause errors or produce inappropriate results, so the program should validate input and prompt again when needed.
- A
- 79
How can a program keep asking for a value until it falls within an acceptable range?
- A
Use a loop that repeats the prompt until validation succeeds, then break out
- B
Use a
switchstatement that runs only once - C
Use a comment to prevent invalid values from being entered
- D
Use a single assignment statement to replace invalid input automatically
Correct answer
AUse a loop that repeats the prompt until validation succeeds, then break out
Explanation
A repeated loop can prompt for input, check whether it is valid, and use
breakonce the value passes validation. - A
- 80
Why should a program use named constants instead of unexplained numeric literals for values such as months per year?
- A
Named constants explain the meaning of values and help avoid magic numbers
- B
Named constants make numeric types compatible with strings
- C
Named constants allow variables to change their values more often
- D
Named constants remove the need for input validation
Correct answer
ANamed constants explain the meaning of values and help avoid magic numbers
Explanation
A named constant such as
MONTHS_IN_YEARmakes code more understandable than an unexplained literal such as12. - A
- 81
What does the equality operator
==test when used with primitive values?- A
Whether the first value is greater than the second
- B
Whether the values are equal
- C
Whether the values are assigned to each other
- D
Whether the values belong to the same package
Correct answer
BWhether the values are equal
Explanation
The equality operator
==compares values; a single=is the assignment operator. - A
- 82
What result does the logical AND operator produce when at least one of its two conditions is false?
- A
true - B
The value of the left condition only
- C
false - D
A syntax error
Correct answer
CfalseExplanation
Logical AND is true only when both conditions are true, so it is false if either condition is false.
- A
- 83
What result does the logical OR operator produce when at least one condition is true?
- A
The value of the last condition only
- B
An integer representing the number of true conditions
- C
false - D
true
Correct answer
DtrueExplanation
Logical OR is true when at least one of its conditions is true.
- A
- 84
What does the logical NOT operator do to a boolean value?
- A
It assigns a value to a variable
- B
It reverses the value from
truetofalseor fromfalsetotrue - C
It combines two conditions into one
- D
It checks whether two strings have equal text
Correct answer
BIt reverses the value from
truetofalseor fromfalsetotrueExplanation
Logical NOT negates a boolean value, reversing true and false.
- A
- 85
Why is an
else ifcondition unnecessary when it is logically implied by the failure of an earlier condition?- A
An
else ifbranch always runs after anifbranch - B
The compiler automatically converts every
else ifto a loop - C
The earlier condition’s failure already establishes the fact needed for that branch
- D
Java does not permit
else ifconditions
Correct answer
CThe earlier condition’s failure already establishes the fact needed for that branch
Explanation
For example, if the only alternatives are a temperature above 30 and then a remaining case, failure of the first test already implies it is no greater than 30.
- A
- 86
When is the ternary operator useful?
- A
When comparing a value against many unrelated classes
- B
When repeating a block an unknown number of times
- C
When selecting one of two values based on a condition and assigning the result
- D
When creating an array with a variable length
Correct answer
CWhen selecting one of two values based on a condition and assigning the result
Explanation
The ternary operator evaluates a condition and yields one value if it is true and another if it is false, which is useful for concise conditional assignments.
- A
- 87
What is the role of a
defaultclause in aswitchstatement?- A
It provides code to execute when none of the listed cases matches
- B
It declares a default value for every variable in the program
- C
It exits the switch before any case is checked
- D
It marks the first case that must always execute
Correct answer
AIt provides code to execute when none of the listed cases matches
Explanation
The
defaultclause runs when none of the switch’s case values matches the expression. - A
- 88
Why are cases in a Java
switchcommonly followed bybreak?- A
To declare the value being compared
- B
To prevent the case expression from being evaluated
- C
To restart evaluation from the first case
- D
To exit the switch instead of continuing into subsequent case code
Correct answer
DTo exit the switch instead of continuing into subsequent case code
Explanation
A
breakexits the switch. Without it, execution can continue into statements associated with later cases. - A
- 89
Why should the most specific condition be checked before more general conditions in a sequence of
ifandelse ifbranches?- A
Specific conditions are always slower to evaluate
- B
A specific condition cannot appear after an
else if - C
Java requires conditions to be ordered alphabetically
- D
A general condition might otherwise match first and prevent the specific branch from running
Correct answer
DA general condition might otherwise match first and prevent the specific branch from running
Explanation
In a first-match conditional chain, a broad condition may be true before a more specific one, so the specific case should be tested first.
- A
- 90
What distinguishes a
forloop from awhileloop in the examples?- A
A
forloop is used only for strings, while awhileloop is used only for numbers - B
A
forloop can run only once, while awhileloop runs forever - C
A
whileloop always has a counter, while aforloop never does - D
A
forloop groups initialization, condition, and update; awhileloop separates them
Correct answer
DA
forloop groups initialization, condition, and update; awhileloop separates themExplanation
A
forloop places the loop variable initialization, continuation condition, and update in its header; awhileloop typically keeps initialization and updating elsewhere. - A
- 91
When is a
forloop especially suitable?- A
When the number of repetitions is known or can be controlled with a counter
- B
When the loop must always execute at least once
- C
When the program must stop as soon as it reads any input
- D
When iterating over a string without examining its characters
Correct answer
AWhen the number of repetitions is known or can be controlled with a counter
Explanation
A
forloop is convenient when the repetition count is known or can be controlled by a loop counter. - A
- 92
When is a
whileloop especially suitable?- A
When the program has no condition to test
- B
When the number of repetitions is not known in advance and depends on a condition
- C
When a block must be executed exactly once
- D
When an array’s elements must be printed without any condition
Correct answer
BWhen the number of repetitions is not known in advance and depends on a condition
Explanation
A
whileloop is useful when repetition depends on a condition, such as continuing to prompt until the user entersquit. - A
- 93
What is the key execution difference between a
do-whileloop and awhileloop?- A
A
do-whileloop checks its condition before the body, so it may never run - B
A
do-whileloop iterates only over arrays - C
A
do-whileloop cannot contain a break statement - D
A
do-whileloop checks its condition after the body, so it runs at least once
Correct answer
DA
do-whileloop checks its condition after the body, so it runs at least onceExplanation
A
do-whileloop checks its condition after executing the body, so it executes at least once even if the condition is initially false. - A
- 94
What does the
breakstatement do inside a loop?- A
It terminates the loop
- B
It skips only the current iteration and proceeds to the next one
- C
It restarts the loop from its initialization
- D
It pauses the program until the user enters a value
Correct answer
AIt terminates the loop
Explanation
breakexits the loop immediately. - A
- 95
What does the
continuestatement do inside a loop?- A
It skips the remaining statements in the current iteration and proceeds to the next iteration
- B
It terminates the loop permanently
- C
It restarts the whole program
- D
It exits the method that contains the loop
Correct answer
AIt skips the remaining statements in the current iteration and proceeds to the next iteration
Explanation
continuemoves control to the next iteration, skipping the rest of the current iteration’s body. - A
- 96
Why must a loop written as
while (true)have a suitable exit mechanism?- A
Otherwise, the loop body is never executed
- B
Otherwise, the condition changes automatically to false
- C
Otherwise, the compiler converts it into a
forloop - D
Otherwise, the loop may continue indefinitely
Correct answer
DOtherwise, the loop may continue indefinitely
Explanation
The condition
truenever becomes false by itself, so the loop needs an exit such as abreakstatement to avoid running forever. - A
- 97
What is a limitation of a for-each loop compared with a traditional indexed
forloop?- A
It cannot iterate over arrays
- B
It does not directly provide the index of each item
- C
It can iterate only from the end toward the beginning
- D
It requires a separate counter to access each item
Correct answer
BIt does not directly provide the index of each item
Explanation
A for-each loop provides each element’s value but not its index; an indexed
forloop makes the index available. - A
- 98
Which statement about for-each iteration is correct in the described examples?
- A
It changes the fixed length of the array as it iterates
- B
It is appropriate only when the array’s index is required
- C
It moves forward through the elements and is convenient when only each value is needed
- D
It can move both forward and backward without additional code
Correct answer
CIt moves forward through the elements and is convenient when only each value is needed
Explanation
A for-each loop conveniently visits array elements in forward order when the index is not needed; a traditional loop offers more control over direction and indexing.
- A
- 99
Why can extracting code into smaller methods improve a long
mainmethod?- A
It removes the need to choose appropriate variable types
- B
It can make the program easier to read, understand, and maintain
- C
It makes all methods accessible from every class
- D
It guarantees that the program uses less memory
Correct answer
BIt can make the program easier to read, understand, and maintain
Explanation
Breaking a long method into smaller, focused chunks improves readability and maintainability by making the program’s parts easier to understand.
- A
- 100
What does the programming principle DRY stand for?
- A
Direct runtime yield
- B
Declare references yearly
- C
Don’t repeat yourself
- D
Data returns yesterday
Correct answer
CDon’t repeat yourself
Explanation
DRY means “Don’t repeat yourself”: avoid unnecessary duplication of code or logic.
- A
- 101
Why might a programmer choose a slightly repetitive flat conditional over a nested conditional?
- A
Repetition makes the program execute fewer instructions
- B
A flat conditional automatically validates user input
- C
The flat structure may be easier to read, even if it repeats some logic
- D
Nested conditionals are always invalid Java
Correct answer
CThe flat structure may be easier to read, even if it repeats some logic
Explanation
Programming solutions involve trade-offs. A flat structure with some repetition can be clearer than nested conditionals that are harder to follow.
- A

Ask anything
We've read this whole study set, so questions about it get the best answers.