CCNA Primitives Strings Operators Questions

35 of 112 questions · Page 2/2 · Primitives Strings Operators topic · Answers revealed

76
Multi-Selecthard

Which THREE of the following are valid Java operators?

Select 3 answers
A.::
B.<<
C.instanceof
D.>>>
E.<==
AnswersB, C, D

Shift operator.

Why this answer

Option B (<<) is correct because it is the Java left shift operator, which shifts the bits of an integer or long value to the left by a specified number of positions, filling with zeros. This is a valid bitwise shift operator in Java, defined in the Java Language Specification (JLS §15.19).

Exam trap

Oracle often tests candidates' familiarity with the complete set of Java operators by including plausible but invalid symbols like <== or ::, exploiting the confusion between language constructs and true operators.

77
MCQmedium

Given: int i = 1; int j = i++ + ++i; What is the value of j?

A.3
B.5
C.2
D.4
AnswerD

Correct: i++ = 1, i becomes 2; ++i = 3, i becomes 3; sum 4.

Why this answer

Option C is correct: First, i++ uses 1 then increments i to 2; then ++i increments i to 3 and uses 3; so j = 1 + 3 = 4. Option A is from assuming postfix only. Option B from prefix only.

Option D from incorrect order.

78
MCQeasy

A developer writes: int a = 9; int b = 2; double result = a / b; System.out.println(result); What is the output?

A.4
B.4.0
C.Compilation error
D.4.5
AnswerB

Integer division yields 4, stored as double.

Why this answer

Option A is correct because integer division truncates the fractional part; 9/2 = 4, then assigned to double gives 4.0. Option B is wrong because no explicit cast. Option C is wrong because integer division does not produce 4.5.

Option D is wrong because division is performed before assignment.

79
MCQhard

Which of the following statements about the String class is true?

A.Strings can be modified using the '+' operator
B.String objects can be created only with the 'new' keyword
C.Strings are immutable
D.String is a primitive type
AnswerC

Correct: once created, a String object cannot be changed.

Why this answer

Option C is correct because String objects in Java are immutable, meaning once a String object is created, its value cannot be changed. Any operation that appears to modify a String, such as concatenation, actually creates a new String object. This immutability is a fundamental design choice that enables String pooling, thread safety, and efficient caching of hash codes.

Exam trap

Oracle often tests the misconception that the '+' operator modifies the original String, leading candidates to choose option A, when in fact it creates a new String object and the original remains unchanged.

How to eliminate wrong answers

Option A is wrong because the '+' operator does not modify the original String; it creates a new String object that is the concatenation of the operands, leaving the original String unchanged. Option B is wrong because String objects can be created using string literals (e.g., "hello") without the 'new' keyword, which leverages the string constant pool. Option D is wrong because String is a reference type (a class in java.lang), not a primitive type like int, double, or boolean.

80
Multi-Selectmedium

Which two statements are true about primitive data types in Java?

Select 2 answers
A.The long data type can store values from -2^63 to 2^63-1.
B.The short data type can store values from -32,768 to 32,767.
C.The float data type is 32-bit and can represent decimal numbers precisely.
D.The boolean data type has a size of 1 bit.
E.The char data type can store only ASCII characters.
AnswersA, B

Correct: long is 64-bit signed two's complement.

Why this answer

Option A and E are correct. The long data type ranges from -2^63 to 2^63-1, and the short data type ranges from -32,768 to 32,767. Option B is false because char stores Unicode characters, not just ASCII.

Option C is false because float is not precise for decimal numbers. Option D is false because the boolean data type size is not strictly defined and typically is not a single bit.

81
Multi-Selectmedium

Which three of the following are valid Java operators that can be used with primitive numeric types?

Select 3 answers
A.&
B.^
C.|
D.||
E.&&
AnswersA, B, C

& is a bitwise AND operator that works on integer types (byte, short, int, long, char).

Why this answer

Option A (&) is correct because the bitwise AND operator can be applied to any primitive numeric type (byte, short, int, long, char, float, double) to perform a bitwise operation on their binary representations. It operates on each bit independently, returning 1 only if both corresponding bits are 1.

Exam trap

Oracle often tests the distinction between short-circuit logical operators (&&, ||) and bitwise operators (&, |, ^), trapping candidates who assume that && and || can be used with numeric types because they look similar to & and |.

82
MCQmedium

A scientific application performs calculations with double precision. A specific formula divides two double values: result = a / b; where a and b are calculated from sensor readings. The result is expected to be at most 10 decimal digits of precision. However, the output often shows small rounding errors, e.g., 0.1 + 0.2 = 0.30000000000000004. The application must meet strict accuracy requirements and cannot tolerate these small errors. Which strategy should be used to achieve exact decimal representation?

A.Use BigDecimal with an appropriate scale and rounding mode.
B.Apply Math.round() to the result to reduce decimal places.
C.Use the float data type instead of double to reduce memory usage.
D.Cast the result to int after multiplying by a power of 10.
AnswerA

BigDecimal represents decimal numbers exactly and allows controlling precision and rounding, eliminating floating-point rounding errors.

Why this answer

Floating-point arithmetic inherently has rounding errors due to binary representation. BigDecimal provides arbitrary-precision decimal arithmetic and allows specifying rounding modes, making it ideal for exact calculations. Option B is the correct approach.

Option A (using float) reduces precision and worsens errors. Option C (Math.round) rounds to integer, not applicable. Option D (casting to int) truncates and loses fractional part.

83
Multi-Selectmedium

Which TWO of the following are valid declarations and initializations of primitive variables?

Select 2 answers
A.double d = 10.5;
B.float f = 10.5;
C.int i = 10;
D.byte b = 200;
E.long l = 123456789012;
AnswersA, C

Valid double initialization.

Why this answer

Options A and D are correct. A: int i = 10; D: double d = 10.5; B: long without L suffix (compile error because 123456789012 > int max). C: byte with value out of range.

E: float without f suffix (default double).

84
MCQeasy

Which primitive type has a default value of 0.0f?

A.float
B.long
C.double
D.int
AnswerA

float default is 0.0f.

Why this answer

In Java, the default value for a float primitive is 0.0f. This is because float is a 32-bit IEEE 754 floating-point type, and its default initialization is 0.0f (with the 'f' suffix to denote a float literal). Option A is correct because it directly matches this specification.

Exam trap

Oracle often tests the distinction between float and double default values, where candidates mistakenly choose double (0.0d) because they overlook the 'f' suffix requirement for float literals.

How to eliminate wrong answers

Option B is wrong because long has a default value of 0L, not 0.0f; long is a 64-bit integer type. Option C is wrong because double has a default value of 0.0d, not 0.0f; double is a 64-bit floating-point type. Option D is wrong because int has a default value of 0, not 0.0f; int is a 32-bit integer type.

85
MCQeasy

Which of the following is a valid Java primitive type?

A.boolean
B.String
C.Integer
D.Char
AnswerA

Correct: boolean is one of the eight primitive types in Java.

Why this answer

Option A is correct because `boolean` is one of the eight primitive data types defined in the Java Language Specification (JLS §4.2). It represents a single bit of information with only two possible values: `true` or `false`, and is not an object or a reference type.

Exam trap

The trap here is that candidates confuse case-sensitive naming (e.g., `Char` vs `char`) or mistake commonly used reference types like `String` and `Integer` for primitives because they are frequently used in everyday coding.

How to eliminate wrong answers

Option B is wrong because `String` is a class in the `java.lang` package, not a primitive type; it is an immutable reference type that stores sequences of characters. Option C is wrong because `Integer` is a wrapper class for the primitive `int` type, part of the `java.lang` package, and is a reference type, not a primitive. Option D is wrong because `Char` with a capital 'C' is not a valid Java primitive type; the correct primitive type is `char` (lowercase), which is a 16-bit Unicode character.

86
MCQmedium

Refer to the exhibit. What is the output?

A.Compilation error
B.25
C.17
D.21
AnswerC

Multiplication has higher precedence than addition.

Why this answer

Option B is correct: a*b = 15, then +2 = 17. Option A is wrong (multiplication first). Option C is wrong (assuming parentheses around b+2).

Option D is wrong because no error.

87
MCQmedium

What is the output of the following code? int i = 0; i = i++ + ++i; System.out.println(i);

A.3
B.0
C.1
D.2
AnswerD

Correct: i=0, i++ gives 0 (i=1), ++i gives 2 (i=2), 0+2=2.

Why this answer

Option D is correct because the expression `i = i++ + ++i` evaluates as follows: initially `i = 0`. In `i++`, the post-increment operator returns the current value (0) and then increments `i` to 1. Then `++i` pre-increments `i` from 1 to 2 and returns 2.

The sum is 0 + 2 = 2, which is assigned to `i`, overwriting the intermediate increments. Thus, the final output is 2.

Exam trap

The trap here is that candidates often misapply operator precedence or confuse the order of evaluation with the order of side effects, specifically forgetting that post-increment returns the original value before the increment, while pre-increment returns the value after the increment.

How to eliminate wrong answers

Option A is wrong because 3 would result from incorrectly assuming both increments happen before the addition (e.g., i becomes 1 then 2, then 1+2=3, but the post-increment returns the original value, not the incremented one). Option B is wrong because 0 would result from mistakenly thinking the assignment uses the original value of i (0) and ignores the increments entirely. Option C is wrong because 1 would result from a common error of only counting one increment or misordering the operations (e.g., thinking i++ increments first, then ++i adds 1 to the already incremented value, yielding 1+1=2 but then assigning incorrectly).

88
MCQhard

A method returns a String. The team debates using == vs equals(). Which correctly describes String comparison in Java?

A.== compares the content of two Strings.
B.== always returns false for different String objects, even if content is same.
C.equals() compares the memory addresses.
D.== may return true for two different references if they point to the same interned string.
AnswerD

String literals are interned; == can be true for same literal.

Why this answer

Option D is correct because the == operator in Java compares object references, not content. However, due to string interning, two different String variables that reference the same interned string literal will have the same memory reference, causing == to return true. This is a special case that can mislead developers into thinking == compares content.

Exam trap

The trap here is that candidates often assume == always compares references and never returns true for equal content, but they forget about string interning, which can cause == to return true for two different references pointing to the same interned string.

How to eliminate wrong answers

Option A is wrong because == compares memory addresses (references), not the content of Strings. Option B is wrong because == can return true for different String objects if they are interned and point to the same memory location. Option C is wrong because equals() compares the actual character content of the Strings, not memory addresses.

89
MCQhard

What is the value of y?

A.22
B.20
C.21
D.23
AnswerA

Correct.

Why this answer

The code snippet likely performs an operation such as `int y = 10 + 12;` or similar arithmetic, resulting in y = 22. In Java, primitive integer addition follows standard arithmetic rules, and the value 22 is directly computed without any overflow or type conversion issues.

Exam trap

Oracle often tests the candidate's attention to basic arithmetic with integer literals, where a simple misreading of the operands or operator leads to selecting a plausible but incorrect sum.

How to eliminate wrong answers

Option B is wrong because 20 would result from an incorrect operation like subtracting 2 instead of adding, or misreading the operands. Option C is wrong because 21 would come from a miscalculation such as 10 + 11 or a off-by-one error. Option D is wrong because 23 would require an extra increment or addition of 1 beyond the correct sum.

90
MCQeasy

Given: int x = 3 + 4 * 2; What is x?

A.11
B.11
C.24
D.14
AnswerB

Correct result.

Why this answer

Multiplication has higher precedence, so 4*2=8, then 3+8=11.

91
MCQhard

Why does the code output false?

A.s1 is created with 'new' thus not in string pool, s2 is literal in pool, so different references
B.s1 and s2 refer to different objects in the heap
C.The String class does not override equals
D.The == operator compares value not reference
AnswerA

Correct: this explains the difference in references.

Why this answer

The new keyword forces creation of a new String object in heap. The literal "Java" is interned and may be in the string pool. s1 and s2 refer to different objects, so == returns false.

92
MCQeasy

What is the value of 10 % 3?

A.0
B.1.0
C.3
D.1
AnswerD

Correct: 10 ÷ 3 = 3 remainder 1.

Why this answer

The % operator returns remainder of division. 10 divided by 3 is 3 with remainder 1.

93
MCQhard

A financial trading application processes a batch of 10 million trade transactions every night. Each transaction is a String containing trade details such as ID, symbol, quantity, and price. The current implementation uses string concatenation with the += operator in a loop to build a summary report string. The application frequently runs out of memory and takes hours to complete. The server has 16 GB of RAM and runs Java 11. The code cannot be restructured significantly due to regulatory requirements, but performance improvements are allowed. Which course of action will most effectively resolve the performance and memory issues?

A.Replace the String concatenation with StringBuilder.
B.Call intern() on the concatenated result at each iteration.
C.Increase the JVM heap size to 32 GB to accommodate the temporary string objects.
D.Replace the String concatenation with StringBuffer.
AnswerA

StringBuilder is mutable and appends to the same buffer, drastically reducing object creation and improving performance. It is the standard solution for repeated string concatenation.

Why this answer

String concatenation using += inside a loop creates many intermediate String objects, leading to memory waste and slowness. StringBuilder is mutable and designed for efficient string building without creating multiple intermediate objects. Option C is the optimal fix.

Option A (heap increase) only delays the problem. Option B (StringBuffer) is thread-safe but slower due to synchronization, unnecessary in a single-threaded context. Option D (using intern()) does not improve efficiency and can harm performance.

94
Multi-Selecteasy

Which THREE of the following statements about operators in Java are true?

Select 3 answers
A.The instanceof operator can be used to check if an object is an instance of a class.
B.The right shift operator (>>) always fills with zeros.
C.The assignment operator (=) has the lowest precedence.
D.The equality operator (==) compares the content of objects.
E.The conditional operator (&&) short-circuits: if left operand is false, right operand is not evaluated.
AnswersA, C, E

Correct usage.

Why this answer

Option A is correct because the `instanceof` operator in Java is a binary operator used to test whether an object is an instance of a specific class, subclass, or interface. It returns `true` if the object is an instance of the specified type, otherwise `false`, and is commonly used for type checking before casting.

Exam trap

Oracle often tests the misconception that `==` compares object content for reference types, when in fact it compares references, and that `>>` always fills with zeros, confusing it with the unsigned right shift `>>>`.

95
MCQmedium

A developer needs to concatenate several string values in a loop. Which approach is most efficient for performance?

A.Using StringBuilder
B.Using String.concat()
C.Using the '+' operator inside the loop
D.Using StringBuffer
AnswerA

Correct: StringBuilder provides mutable sequence and is optimized for such use.

Why this answer

StringBuilder is the most efficient approach for concatenating strings in a loop because it maintains a mutable sequence of characters, avoiding the creation of intermediate String objects. In contrast, using the '+' operator or String.concat() inside a loop results in the allocation of a new String object for each concatenation, leading to O(n²) time complexity and increased garbage collection overhead.

Exam trap

Oracle often tests the misconception that the '+' operator is always optimized by the compiler, but in a loop it creates a new StringBuilder per iteration, making it far less efficient than using a single StringBuilder outside the loop.

How to eliminate wrong answers

Option B is wrong because String.concat() creates a new String object for each concatenation, which is inefficient in a loop due to repeated object allocation and copying. Option C is wrong because the '+' operator compiles to StringBuilder.append() only when used in a single expression; inside a loop, each iteration creates a new StringBuilder, resulting in the same performance penalty as explicit String concatenation. Option D is wrong because StringBuffer is thread-safe with synchronized methods, which adds unnecessary overhead in a single-threaded context, making it slower than StringBuilder.

96
Multi-Selectmedium

Which THREE of the following expressions evaluate to true? (Assume int a=5, b=10)

Select 3 answers
A.a == b
B.a < b
C.a >= b
D.a != b
E.b > a
AnswersB, D, E

5 < 10 true.

Why this answer

Option B is correct because the expression 'a < b' compares the integer values of a (5) and b (10). Since 5 is less than 10, the relational operator '<' returns the boolean value true.

Exam trap

Oracle often tests the distinction between assignment (=) and equality (==) operators, but here the trap is that candidates may confuse the direction of the comparison or forget that 'a != b' is true when values differ, leading them to incorrectly eliminate correct options like D and E.

97
MCQeasy

What is the result of the following code snippet? int x = 5; int y = 2; double z = x / y; System.out.println(z);

A.3.0
B.2
C.2.0
D.2.5
AnswerC

Correct: integer division yields 2, then assigned to double becomes 2.0.

Why this answer

Option C is correct because in Java, when both operands of the division operator are integers (int), the operation performs integer division, which truncates the fractional part. Here, x / y = 5 / 2 = 2 (integer division), and then the result is implicitly widened to double when assigned to z, producing 2.0.

Exam trap

The trap here is that candidates often forget Java performs integer division when both operands are integers, mistakenly assuming the result will be a floating-point value like 2.5 just because the variable is declared as double.

How to eliminate wrong answers

Option A is wrong because it suggests the result is 3.0, which would only occur if the division were 5 / 1.666... or if rounding occurred, but Java integer division truncates toward zero, not rounds. Option B is wrong because it outputs 2 (an int), but the variable z is declared as double, so the printed value will have a decimal point, i.e., 2.0, not 2. Option D is wrong because it assumes floating-point division occurs, but since both operands are int, integer division is performed first, yielding 2, not 2.5.

98
MCQmedium

A developer writes: String s = "Hello"; s.concat(" World"); System.out.println(s); What is the output?

A.Compilation fails
B.Hello World
C.Hello
D.Hello World
AnswerC

Correct because concat does not modify s.

Why this answer

Option C is correct because strings in Java are immutable. The `concat()` method returns a new string but does not modify the original string `s`. Since the return value is not assigned to any variable, the original string `s` remains unchanged, so `System.out.println(s)` prints "Hello".

Exam trap

The trap here is that candidates often forget that strings are immutable and assume methods like `concat()` modify the original object, leading them to choose "Hello World" instead of "Hello".

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; `concat()` is a valid method on String objects. Option B is wrong because it assumes `concat()` modifies the original string, but strings are immutable in Java. Option D is wrong for the same reason as B — it incorrectly expects the concatenated result to be printed.

99
MCQmedium

A developer wants to assign the largest possible long value to a variable. Which is correct?

A.long x = (long) 9223372036854775807L;
B.long x = 9223372036854775808L;
C.long x = 9223372036854775807;
D.long x = 9223372036854775807L;
E.long x = Long.MAX_VALUE;
.long x = 9223372036854775807;
.long x = (long) 1e19;
AnswerE

Correct constant.

Why this answer

Option E is correct because Long.MAX_VALUE is a predefined constant in the Java Long wrapper class that holds the maximum possible long value, which is 9223372036854775807. Using this constant ensures portability and avoids hardcoding errors, as the literal value 9223372036854775807 is within the valid long range and must be suffixed with 'L' to be treated as a long literal.

Exam trap

The trap here is that candidates often forget the 'L' suffix for long literals or attempt to assign a value that exceeds the long range, leading them to choose options that cause compilation errors, while the correct answer leverages the Long.MAX_VALUE constant to avoid such pitfalls.

How to eliminate wrong answers

Option A is wrong because the cast (long) is redundant and the literal 9223372036854775807L already has the correct suffix, but the cast does not cause an error; however, the option is not the best practice and is not the correct answer. Option B is wrong because 9223372036854775808L exceeds Long.MAX_VALUE (9223372036854775807) and will cause a compilation error 'integer number too large'. Option C is wrong because the literal 9223372036854775807 lacks the 'L' suffix, so it is treated as an int literal, which is too large for int and causes a compilation error.

Option D is technically correct as a literal assignment, but it is not the best answer because it uses a hardcoded literal rather than the standard constant. Option null (first) is wrong because it is not a valid option. Option null (second) is wrong because (long) 1e19 is a double literal cast to long, which will truncate and produce a value of 9223372036854775807 (due to double precision limits), but it is not the largest possible long value and is a poor practice.

100
MCQmedium

Evaluate the following expression: int x = 5; int y = (x > 5) ? 10 : 20; What is y?

A.20
B.5
C.Compilation error
D.10
AnswerA

Condition false, assigns 20.

Why this answer

The ternary operator `(x > 5) ? 10 : 20` evaluates the condition `x > 5`. Since `x` is 5, the condition is false, so the expression returns the value after the colon, which is 20. This value is assigned to `y`, making `y` equal to 20.

Exam trap

Oracle often tests the ternary operator by setting the condition to a borderline value (like equality) to see if candidates mistakenly think the true branch is selected when the condition is false.

How to eliminate wrong answers

Option B is wrong because 5 is the value of `x`, not the result of the ternary expression; the ternary operator does not return the variable itself. Option C is wrong because the ternary operator is a valid Java construct and the code compiles without error; the condition `x > 5` is a valid boolean expression. Option D is wrong because 10 is the value returned only when the condition is true, but here `x > 5` is false, so the false branch (20) is selected.

101
MCQmedium

Which of the following is a valid Java identifier?

A.2variable
B.class
C._myVar
D.my-var
AnswerC

Underscore allowed.

Why this answer

Option C (_myVar) is a valid Java identifier because it starts with an underscore, which is permitted by the Java Language Specification. Java identifiers must begin with a letter (A-Z, a-z), dollar sign ($), or underscore (_), and cannot start with a digit or contain hyphens. The underscore is explicitly allowed, making _myVar a legal identifier.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit, but the trap here is that candidates may mistakenly think underscores are invalid or that keywords like 'class' can be used as identifiers if they forget Java's reserved word list.

How to eliminate wrong answers

Option A is wrong because 2variable starts with a digit, which violates the Java rule that identifiers cannot begin with a number. Option B is wrong because class is a reserved keyword in Java and cannot be used as an identifier. Option D is wrong because my-var contains a hyphen (-), which is not a valid character in Java identifiers; only letters, digits, dollar signs, and underscores are allowed.

102
MCQhard

Given: short s = 10; s = s + 5; What is the result?

A.s = 10
B.Runtime exception
C.s = 15
D.Compilation fails: possible lossy conversion from int to short
AnswerD

s + 5 is int, cannot assign to short.

Why this answer

The expression `s + 5` performs arithmetic on a `short` and an `int` literal, so the result is promoted to `int`. Assigning that `int` back to a `short` variable without an explicit cast causes a compilation error because an `int` may be larger than a `short` (16-bit range), leading to possible lossy conversion. Therefore, option D is correct.

Exam trap

Oracle often tests the misconception that arithmetic on smaller numeric types (like `short` or `byte`) stays within that type, when in fact Java promotes them to `int` before the operation, causing a compilation error on assignment back without a cast.

How to eliminate wrong answers

Option A is wrong because it suggests the value remains 10, but the arithmetic operation `s + 5` would compute 15, not 10, and the code fails to compile before any assignment occurs. Option B is wrong because the error is a compile-time error, not a runtime exception; Java catches type mismatch issues during compilation. Option C is wrong because although the mathematical result is 15, the code does not compile due to the lossy conversion from `int` to `short`, so no assignment occurs.

103
MCQeasy

What is the output of System.out.println(1 + 2 + "3" + 4 + 5);?

A.3345
B.12345
C.3"3"45
D.15
AnswerA

String concatenation after first addition.

Why this answer

Java evaluates the expression left-to-right. The first operation is `1 + 2`, which is integer addition, yielding `3`. Then `3 + "3"` triggers string concatenation, producing `"33"`.

The remaining `+ 4` and `+ 5` are also string concatenations, appending `"4"` and `"5"` to give `"3345"`. The `println` method outputs this string.

Exam trap

The trap here is that candidates assume all `+` operators behave the same way, failing to recognize that the presence of a string literal changes the operator's meaning from arithmetic addition to string concatenation, and that left-to-right evaluation means the first two numbers are added as integers before the string is encountered.

How to eliminate wrong answers

Option B is wrong because it assumes all numbers are concatenated as strings from the start, ignoring that `1 + 2` is evaluated as integer addition before any string context. Option C is wrong because it incorrectly includes literal quotes in the output, which Java never prints; the `+` operator does not produce quote characters. Option D is wrong because it sums all numbers as integers (1+2+3+4+5=15), ignoring that the string `"3"` forces subsequent operations to be string concatenation, not arithmetic.

104
Multi-Selecthard

Which TWO of the following operations on String objects result in a new String object?

Select 2 answers
A."Hello".toString()
B."Hello".length()
C."Hello".charAt(0)
D."Hello".replace('l', 'p')
E."Hello".concat(" World")
AnswersD, E

Returns new string with replacements.

Why this answer

Option D is correct because `String.replace()` returns a new `String` object with the replacement applied, as `String` is immutable in Java. The original `"Hello"` remains unchanged, and a new string `"Heppo"` is created.

Exam trap

Oracle often tests the distinction between methods that return a new `String` versus those that return a primitive or the same reference, exploiting the common misconception that all `String` methods modify the original object.

105
Multi-Selectmedium

Which two of the following are valid ways to create a String object?

Select 2 answers
A.String s = "Hello";
B.String s = 12345;
C.String s = (String) new Integer(10);
D.String s = new String("Hello");
E.String s = 'Hello';
AnswersA, D

Valid string literal.

Why this answer

Option A creates a new String object via constructor. Option B creates a string literal. Option C is a char literal and not assignable to String.

Option D is an int literal. Option E is a cast that results in a compile-time error because Integer cannot be cast to String.

106
MCQeasy

What is the default value of a boolean variable in Java?

A.null
B.true
C.false
D.0
AnswerC

Correct.

Why this answer

In Java, the default value of a boolean variable (when declared as a class field or instance variable) is 'false'. This is specified by the Java Language Specification (JLS §4.12.5), which defines default values for all primitive types. Unlike local variables, which must be explicitly initialized, instance and static variables receive default values automatically.

Exam trap

Oracle often tests the distinction between default values for primitives vs. objects, and the trap here is that candidates confuse boolean's default with the default for Boolean (which is null) or mistakenly think boolean defaults to true or a numeric value.

How to eliminate wrong answers

Option A is wrong because 'null' is the default value for object references, not for primitive types like boolean. Option B is wrong because 'true' is not the default; the JLS explicitly states that the default for boolean is false. Option D is wrong because 0 is the default for numeric primitives (int, long, etc.), not for boolean, which is not a numeric type and cannot be assigned 0.

107
Multi-Selectmedium

Which TWO of the following are valid ways to create a String?

Select 2 answers
A.String s = 'Hello';
B.String s = new String("Hello");
C.String s = 123;
D.String s = String.valueOf("Hello");
E.String s = "Hello";
AnswersB, E

Correct.

Why this answer

Option B is correct because it uses the `new` keyword to explicitly create a new String object in the heap, which is a valid way to instantiate a String. Option E is correct because it uses a string literal, which is the most common and efficient way to create a String in Java, leveraging the string constant pool.

Exam trap

Oracle often tests the distinction between string literals and `new String()`, and the trap here is that candidates may think `String.valueOf("Hello")` creates a new String, when it actually returns the same reference from the pool, making it not a valid 'creation' in the exam's intended sense.

108
MCQhard

A developer is working on a Java application that processes user input. The application reads a string from the console and needs to compare it with a predefined constant string "ADMIN". The developer writes the following code: if (input == "ADMIN") { grantAccess(); }. During testing, the condition sometimes fails even when the user enters ADMIN. The input string is obtained via Scanner.nextLine(). Which is the most likely cause and best fix?

A.Use input.equals("ADMIN") instead of ==.
B.Use input.compareTo("ADMIN") == 0.
C.Use input == "ADMIN" with intern() on input.
D.Convert input to char array and compare.
AnswerA

Correct because equals compares values.

Why this answer

Option A is correct because `==` compares object references, not string content. `Scanner.nextLine()` returns a new `String` object, so `input == "ADMIN"` compares references, which are different even if the content matches. Using `input.equals("ADMIN")` compares the actual character sequence, which is the correct way to test string equality in Java.

Exam trap

Oracle often tests the distinction between reference equality (`==`) and value equality (`equals()`) for strings, exploiting the common misconception that `==` compares string content because it works for primitive types.

How to eliminate wrong answers

Option B is wrong because `compareTo()` returns an integer (0 if equal) and is intended for ordering, not simple equality; it works but is less readable and more error-prone than `equals()`. Option C is wrong because calling `intern()` on `input` would force it into the string pool, making `==` work, but this is an unnecessary performance hit and not the idiomatic fix; the standard practice is to use `equals()`. Option D is wrong because converting to a char array and comparing element-by-element is overly complex, inefficient, and not the standard Java approach for string comparison.

109
Multi-Selecthard

Which three of the following are valid ways to declare and initialize a variable of type int? (Choose three.)

Select 3 answers
A.int b = 0xA;
B.int e = 10.0;
C.int d = 010;
D.int c = 0b2;
E.int a = 10;
AnswersA, C, E

Correct: hexadecimal literal 0xA equals 10 decimal.

Why this answer

Option A is correct because `0xA` is a hexadecimal integer literal in Java, representing the decimal value 10. Java allows hexadecimal literals using the prefix `0x` or `0X`, and they are valid for initializing an `int` variable.

Exam trap

Oracle often tests the distinction between valid integer literal formats and invalid ones, such as using a digit 2 in a binary literal or assigning a floating-point literal without a cast, which candidates might overlook due to familiarity with other languages.

110
MCQmedium

A developer is implementing a login verification method that compares a user-entered password against a stored hash. The passwords are stored as String objects. Which approach ensures correct comparison?

A.if (enteredPassword.compareTo(storedHash) == 0)
B.if (enteredPassword.equals(storedHash))
C.if (enteredPassword == storedHash)
D.if (enteredPassword.hashCode() == storedHash.hashCode())
AnswerB

Compares string content correctly.

Why this answer

Option B is correct because String.equals() compares the actual content. Option A uses reference equality, which is incorrect. Option C uses hash codes which may have collisions.

Option D uses compareTo which is for lexicographic order, not equality.

← PreviousPage 2 of 2 · 112 questions total

Ready to test yourself?

Try a timed practice session using only Primitives Strings Operators questions.