Courseiva

CCNA Primitives, Strings and Operators Questions

30 of 105 questions · Page 2/2 · Primitives, Strings and Operators · Answers revealed

76
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

Options A, B, and C are correct because &, ^, and | are bitwise operators that can be applied to integral primitive numeric types (byte, short, int, long, char). They operate on the binary representations of these types. Note that these operators are not applicable to floating-point types (float, double).

Options D and E (&&, ||) are logical operators that work only with boolean operands, not numeric types.

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

77
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 (double) inherently has rounding errors due to binary representation, as shown in the example 0.1 + 0.2 = 0.30000000000000004. BigDecimal provides arbitrary-precision decimal arithmetic and allows specifying scale and rounding modes, making it ideal for exact decimal calculations meeting the 10-digit precision requirement. Therefore, Option A (BigDecimal) is the correct approach.

Option B (Math.round) rounds to an integer, losing fractional precision. Option C (float) uses less precision than double, worsening errors. Option D (casting to int after scaling) truncates and risks loss of information.

78
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 C are correct. A: double d = 10.5; is valid because a double literal can be assigned without suffix. C: int i = 10; is valid because 10 fits in an int.

B: float f = 10.5; is invalid because 10.5 is a double literal; must use f suffix. D: byte b = 200; is invalid because 200 is out of byte range (-128 to 127). E: long l = 123456789012; is invalid because the literal exceeds int range and lacks L suffix.

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

80
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

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

81
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

The expression `a * b + 2` follows Java operator precedence: multiplication has higher precedence than addition, so it evaluates as `(a * b) + 2`. Given `a = 3` and `b = 5`, `3 * 5 = 15`, then `15 + 2 = 17`. Therefore, option C is correct.

Option A is wrong because the code compiles successfully (no error). Option B (25) would result from `(a + b) * 2` or similar misinterpretation. Option D (21) would result from `a * (b + 2)`.

Only option C matches the correct calculation.

82
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

The output is 2 because Java evaluates the right-hand side of the assignment `i = i++ + ++i;` from left to right. First, `i++` uses the current value of `i` (0) for the sum, then increments `i` to 1. Next, `++i` pre-increments `i` to 2, then uses this new value (2) for the sum. The addition becomes `0 + 2`, resulting in 2, which is then assigned back to `i`. This demonstrates the precise order of operator precedence and side effects in Java's expression evaluation.

Why this answer

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

83
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

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.

84
MCQhard

What is the value of y after executing the following code? ```java int y = 10 + 12; ```

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

The value of y is 22 because Java's operator precedence rules dictate that multiplication operations are evaluated before addition. For an expression like `10 + 3 * 4`, the `3 * 4` calculation is performed first, yielding 12. Subsequently, 10 is added to this intermediate result, satisfying the requirement for the final value of y to be 22 by correctly applying the order of operations.

Why this answer

The code snippet `int y = 10 + 12;` performs integer addition, resulting in y = 22. Java's primitive arithmetic follows standard rules, so adding 10 and 12 yields 22 without any overflow or 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.

85
MCQeasy

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

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

This is the correct value 11.

Why this answer

Multiplication has higher precedence than addition: 4 * 2 = 8, then 3 + 8 = 11. Therefore, x is 11, making option A the correct answer.

86
MCQhard

Given the following code, String s1 = new String("example"); String s2 = "example"; System.out.println(s1 == s2); 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 code likely creates s1 using the 'new' operator, which forces the creation of a new String object in the heap, not in the string pool. s2 is a string literal, which is interned and placed in the string pool. The '==' operator compares object references, so s1 and s2 refer to different objects, hence the comparison returns false.

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

88
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

The performance and memory issues are caused by using String concatenation (+=) inside a loop, which creates many intermediate String objects because Strings are immutable in Java. StringBuilder is mutable and designed for efficient string concatenation without creating intermediate objects, making it the optimal solution. Option A (StringBuilder) is correct.

Option B (calling intern()) would not improve performance and could degrade it. Option C (increasing heap size) only postpones the OutOfMemoryError and does not fix the inefficiency. Option D (StringBuffer) is thread-safe but slower due to synchronization; it is unnecessary in this single-threaded context.

Therefore, replacing concatenation with StringBuilder is the most effective resolution.

89
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

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

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

91
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

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.

92
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

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.

93
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

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.

94
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

This line uses the well-defined constant Long.MAX_VALUE, which is clear and maintainable.

Why this answer

The correct answer is E. Long.MAX_VALUE is the standard and readable way to obtain the maximum long value. While option D (9223372036854775807L) is syntactically valid, it is not recommended because it is error-prone and does not clearly convey intent.

Options A and C are incorrect: A has an unnecessary cast, and C omits the L suffix, causing a compile error. Option B exceeds the long range.

Exam trap

Candidates may be tempted to use a numeric literal with L suffix, but the best practice is to use the Long.MAX_VALUE constant to avoid typos and improve readability.

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.

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

96
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

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

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

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

99
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

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

100
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

String literal, directly assigned to String variable. This is valid because string literals are instances of String.

Why this answer

A string literal, which is a valid way to create a String object. Option D uses the String constructor with a string argument, also valid. Option B assigns an integer literal to a String variable, which is not allowed.

Option C attempts to cast an Integer object to String, which causes a compile-time error because Integer is not a subclass of String. Option E uses a char literal ('Hello' is invalid because char literals are single characters) and is not assignable to String.

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

102
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

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.

103
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

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

104
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

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

105
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

equals() is the standard method for comparing string content.

Why this answer

Option B uses equals(), the standard method for comparing string content, correctly checking character sequences. Option A uses compareTo(), which is intended for ordering; although compareTo() == 0 indicates equality, it is not the idiomatic approach and is considered a trap. Option C uses ==, comparing references, not content.

Option D uses hashCode(), which may collide and does not guarantee equality.

Exam trap

The trap is that compareTo() can return 0 for equal strings, tempting candidates to select it. However, equals() is the expected method for simple equality checks.

← PreviousPage 2 of 2 · 105 questions total

Ready to test yourself?

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