CCNA Primitives Strings Operators Questions

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

1
MCQhard

Given: boolean a = false; boolean b = true; boolean c = true; System.out.println(a || b && c); What is the output?

A.false
B.Compilation fails
C.None of the above
D.true
AnswerD

Correct due to operator precedence.

Why this answer

In Java, the logical AND operator (&&) has higher precedence than the logical OR operator (||). Therefore, the expression `a || b && c` is evaluated as `a || (b && c)`. Given `a = false`, `b = true`, and `c = true`, `b && c` evaluates to `true`, and then `false || true` evaluates to `true`.

Thus, the output is `true`, making option D correct.

Exam trap

The trap here is that candidates often evaluate the expression left-to-right without considering operator precedence, mistakenly thinking `a || b` is evaluated first (which would be `true`) and then `&& c` would produce `true && true` = `true`, but the actual precedence changes the grouping, though in this specific case both orders yield `true`; however, the trap is to test whether you know the precedence rule, not just the outcome.

How to eliminate wrong answers

Option A is wrong because it assumes the expression evaluates to `false`, which would only happen if both sides of the `||` were false, but `b && c` is true. Option B is wrong because the code compiles successfully; all variables are declared with valid boolean literals and the operators are correctly applied. Option C is wrong because 'None of the above' is not correct since option D provides the accurate output.

2
MCQeasy

A developer writes the following code: String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); What is the output?

A.Compilation fails
B.false
C.true
D.Hello
AnswerC

Both references point to the same interned string.

Why this answer

Option C is correct because string literals in Java are interned, meaning both s1 and s2 refer to the same String object in the string constant pool. The == operator compares object references, not content, so since both variables point to the same interned string, the comparison yields true.

Exam trap

The trap here is that candidates often confuse reference equality (==) with value equality (.equals()), assuming == always returns false for distinct string variables, without considering string interning of literals.

How to eliminate wrong answers

Option A is wrong because the code compiles without error; string literals are valid and the == operator is allowed on object references. Option B is wrong because it assumes == compares string content, which would be false only if the strings were created with new String("Hello") or were not interned; here both literals are interned, so references are equal. Option D is wrong because System.out.println does not print the string value when given a boolean expression; it prints the boolean result of the comparison.

3
MCQeasy

A social media platform processes user login requests. Each request generates a welcome message by concatenating the username with a fixed greeting using the + operator inside a loop that runs hundreds of times per second for thousands of users. The development team notices that the application suffers from high memory consumption and slow response times under load. They profile the code and discover that the method building the welcome message is a bottleneck. The team considers several options to improve performance while maintaining thread safety. Which approach should the team implement?

A.Replace string concatenation with StringBuffer and use an initial capacity to minimize resizing.
B.Replace string concatenation with StringBuilder and allocate an initial capacity large enough to hold the final message.
C.Keep using the + operator but call intern() on the resulting string to reuse memory.
D.Replace string concatenation with the concat() method called on the greeting string.
AnswerB

Correct: StringBuilder is efficient and non-synchronized; initial capacity avoids resizing.

Why this answer

Option B is correct: StringBuilder with sufficient initial capacity reduces memory reallocations and is faster than StringBuffer for single-threaded contexts. Option A (StringBuffer) is thread-safe but slower due to synchronization, not needed here since the method is not shared across threads. Option C (concat()) still creates new strings internally, similar to + operator.

Option D (intern()) does not improve performance and may cause memory issues.

4
MCQhard

Which of the following is a valid declaration of a float variable?

A.Both B and C are valid
B.float f = 10.5f;
C.float f = 10.5;
D.float f = 10.5F;
AnswerA

Both f and F suffixes denote float literal.

Why this answer

Float literals require suffix f or F. Without suffix, the literal is double and causes compilation error.

5
MCQmedium

Which operator is used to compare two strings for value equality in Java?

A.compareTo()
B.=
C.==
D.equals()
AnswerD

Correct for value equality.

Why this answer

Option D is correct because the equals() method in Java's String class compares the actual character sequences of two strings for value equality. Unlike the == operator, which checks reference equality (whether two references point to the same object in memory), equals() performs a lexicographic comparison of the string contents, returning true if and only if both strings have the same length and the same characters in the same order.

Exam trap

The trap here is that candidates often confuse == with equals() because == works for primitive types (like int or char) to compare values, but for String objects it compares references, leading to incorrect results when comparing string contents.

How to eliminate wrong answers

Option A is wrong because compareTo() is a method that compares strings lexicographically and returns an integer (negative, zero, or positive) indicating the ordering, not a boolean value for equality. Option B is wrong because = is the assignment operator, used to assign a value to a variable, not a comparison operator. Option C is wrong because == checks reference equality for objects, including strings; it returns true only if both references point to the exact same String object in memory, not if the string contents are equal.

6
MCQhard

Refer to the exhibit. What is the result?

A.Compilation error
B.0
C.Runtime exception
D.Infinity
AnswerC

Correct: ArithmeticException thrown.

Why this answer

The code attempts to divide an integer by zero, which in Java throws an ArithmeticException at runtime. Since the division is performed with integer operands (int / int), Java does not allow division by zero and raises an exception, not a floating-point infinity or zero. Therefore, the correct answer is C: Runtime exception.

Exam trap

Oracle often tests the difference between integer and floating-point division by zero, trapping candidates who assume all division by zero yields Infinity or a compile error, when in fact integer division throws a runtime exception.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; division by zero is a runtime issue, not a compile-time error. Option B is wrong because integer division by zero does not yield 0; it throws an exception instead. Option D is wrong because Infinity is only produced in floating-point arithmetic (e.g., double / 0.0), not in integer division, which throws an exception.

7
Multi-Selecthard

Which three of the following statements about primitive type conversion are true?

Select 3 answers
A.A float can be implicitly converted to long.
B.Implicit widening conversion is allowed from int to long.
C.A boolean can be converted to int using casting.
D.A char can be assigned to an int without cast because char is unsigned 16-bit and int is 32-bit.
E.Narrowing conversion from double to int requires an explicit cast.
AnswersB, D, E

int to long is a widening primitive conversion.

Why this answer

A is true: int to long is widening. B is true: narrowing double to int requires explicit cast. C is false: boolean cannot be cast to numeric types.

D is true: char to int is widening. E is false: float to long requires explicit cast.

8
Multi-Selectmedium

Which TWO statements are true about the String class in Java? (Choose 2)

Select 2 answers
A.String is mutable if created with new.
B.String implements the Cloneable interface.
C.Strings are immutable.
D.String objects can be modified using methods like toUpperCase().
E.The intern() method can add a string to the string pool.
AnswersC, E

Once created, cannot change.

Why this answer

Option A and B are correct. A: Strings are immutable. B: String pool intern method.

C is wrong because Strings are not mutable. D is wrong because String does not implement Cloneable. E is wrong because StringBuilder is mutable.

9
MCQeasy

What is the result of: System.out.println(10 + 20 + "30");

A.102030
B.3030
C.30
D.Compilation fails
AnswerB

Correct because addition then concatenation.

Why this answer

In Java, the '+' operator is left-associative. The expression `10 + 20 + "30"` is evaluated as `(10 + 20) + "30"`, which first performs integer addition to get `30`, then concatenates that integer with the string `"30"`, resulting in the string `"3030"`. The `System.out.println` method then prints the string `3030`.

Exam trap

The trap here is that candidates often assume all '+' operators in a mixed expression perform string concatenation, forgetting that Java evaluates left to right and that integer addition takes precedence until a string operand is encountered.

How to eliminate wrong answers

Option A is wrong because it assumes all operands are concatenated as strings from the start, producing `"102030"`, but Java evaluates left to right, so the first two integers are added numerically before any string concatenation occurs. Option C is wrong because it suggests only the numeric sum `30` is printed, ignoring that the final operation is string concatenation with `"30"`, which yields a string, not an integer. Option D is wrong because the code compiles and runs without error; there is no type mismatch or syntax issue.

10
MCQmedium

A stock trading system calculates daily profit using an int variable. During periods of high volatility, the profit can exceed Integer.MAX_VALUE (2,147,483,647). When this happens, the profit value wraps around to a negative number, leading to incorrect reporting. The lead developer wants to detect the overflow and throw an ArithmeticException rather than silently producing wrong results. The code cannot use long or BigInteger due to legacy constraints. Which approach should be taken?

A.Use bitwise AND with a mask to detect overflow.
B.Use Math.addExact() for the addition and catch or let the exception propagate.
C.Cast the operands to long before addition and then cast back to int.
D.Use BigInteger for the calculation and convert back to int.
AnswerB

Math.addExact precisely detects overflow and throws ArithmeticException, fitting the requirement to alert about overflow.

Why this answer

Math.addExact() performs integer addition with overflow detection, throwing an ArithmeticException if the result overflows. Option A directly addresses the requirement. Option B (BigInteger) changes the data type, which is ruled out.

Option C (casting to long before addition) changes the type, also not allowed. Option D (bitwise operators) is complex and error-prone, and does not inherently detect overflow.

11
MCQeasy

A developer needs to store a currency value with two decimal places. Which primitive type is most appropriate?

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

Commonly used for currency with two decimal places, though BigDecimal is more accurate.

Why this answer

Option B (double) is the most appropriate primitive type for storing a currency value with two decimal places because double is a 64-bit IEEE 754 floating-point type that can represent fractional values with sufficient precision for typical monetary amounts. While float (32-bit) could also store decimals, double provides higher precision (15-16 significant digits) and is the default type for decimal literals in Java, making it the standard choice for currency calculations in the exam context.

Exam trap

The trap here is that candidates often choose float thinking it is sufficient for decimal values, but they overlook that double is the default type for decimal literals in Java and provides greater precision, which is critical for currency to avoid rounding errors in calculations.

How to eliminate wrong answers

Option A (float) is wrong because float is a 32-bit IEEE 754 floating-point type with only 6-7 significant digits of precision, which can lead to rounding errors when representing currency values with two decimal places, especially in calculations involving large amounts or repeated operations. Option C (long) is wrong because long is a 64-bit integer type that cannot store fractional values at all, making it unsuitable for currency values that require decimal places. Option D (int) is wrong because int is a 32-bit integer type that cannot represent decimal places, so it cannot store a currency value like 12.99.

12
Matchingmedium

Match each Java tool to its function.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Compiles .java source files into .class bytecode

Launches the Java application (JVM)

Generates API documentation from source code comments

Creates and manages JAR archives

Debugger for Java programs

Why these pairings

These tools are part of the JDK.

13
MCQeasy

Which of the following is NOT a primitive data type?

A.int
B.boolean
C.char
D.String
AnswerD

String is a reference type, not primitive.

Why this answer

String is a class in Java, not a primitive data type. The eight primitive types are byte, short, int, long, float, double, boolean, and char. String is a reference type that stores a sequence of characters as an object.

Exam trap

Oracle often tests the misconception that String is a primitive because it is commonly used and has special language support (e.g., string literals and the + operator), but it is actually a reference type from the java.lang package.

How to eliminate wrong answers

Option A is wrong because int is a primitive data type that stores 32-bit signed integers. Option B is wrong because boolean is a primitive data type that stores true or false values. Option C is wrong because char is a primitive data type that stores a single 16-bit Unicode character.

14
MCQhard

Given: byte b = 10; b = b + 1; What is the result?

A.Runtime exception
B.b becomes 10
C.Compilation error
D.b becomes 11
AnswerC

Correct: b+1 is int, cannot assign to byte without explicit cast.

Why this answer

In Java, arithmetic operations on byte promote the result to int. Assigning an int to a byte without a cast causes a compilation error.

15
MCQhard

Refer to the exhibit. What is the output?

A.HelloWorld
B.Hello World
C.Compilation error
D.Hello
AnswerD

String is immutable, s unchanged.

Why this answer

The code prints 'Hello' because the `String` variable `str` is assigned the value `"Hello"` and then `str.concat("World")` is called. However, `String` objects are immutable in Java, so `concat()` returns a new string without modifying the original `str`. Since the result of `concat()` is not assigned back to `str`, the original `str` remains `"Hello"`, and `System.out.println(str)` outputs `Hello`.

Exam trap

Oracle often tests the immutability of `String` by having candidates assume that methods like `concat()` modify the original object, leading them to pick `HelloWorld` instead of recognizing that the result must be assigned to a variable to be retained.

How to eliminate wrong answers

Option A is wrong because it assumes `str` is modified to `"HelloWorld"` and printed, but `concat()` does not change the original string; it returns a new string that is discarded. Option B is wrong because it expects a space between 'Hello' and 'World', but the code concatenates without a space, and even if concatenation worked, the output would be `HelloWorld`, not `Hello World`. Option C is wrong because the code compiles successfully; `concat()` is a valid method on `String` objects, and there is no syntax or type error.

16
MCQeasy

A developer writes: boolean b = !true && false; What is the value of b?

A.Compilation error: invalid operator.
B.false
C.NullPointerException
D.true
AnswerB

!true -> false; false && false -> false.

Why this answer

The expression `!true && false` is evaluated as `(!true) && false`, which is `false && false`. The logical AND (`&&`) operator returns `true` only if both operands are `true`; otherwise, it returns `false`. Therefore, `b` is assigned `false`.

Option B is correct.

Exam trap

The trap here is that candidates may misinterpret the precedence and think `!true && false` is evaluated as `!(true && false)` (which would be `true`), but in Java, the logical NOT (`!`) has higher precedence than logical AND (`&&`), so `!true` is evaluated first.

How to eliminate wrong answers

Option A is wrong because the `!` (logical NOT) and `&&` (logical AND) operators are valid in Java for boolean expressions; no compilation error occurs. Option C is wrong because `NullPointerException` is a runtime exception that occurs when accessing a method or field on a null object reference, not from boolean primitive operations. Option D is wrong because `!true` evaluates to `false`, and `false && false` evaluates to `false`, not `true`.

17
MCQeasy

A developer is implementing a login system where users enter a password that is then hashed using SHA-256. The system stores the hash as a String in the database. On login, the entered password is hashed and compared to the stored hash using the == operator. Occasionally, valid users are denied access, even though the hashes are identical when printed. The developer has confirmed that the hash algorithm is correctly implemented and that the stored hash is exactly the same string as the computed hash. What is the most likely cause and correct fix?

A.Change the comparison from == to equals().
B.Use hashCode() to compare integer representations.
C.Call intern() on both hash strings before using ==.
D.Use compareTo() which returns 0 if equal.
AnswerA

equals() compares the actual characters of the strings, which is appropriate for password hash comparison.

Why this answer

The == operator compares object references, not string content. Even if the two hash strings are logically equal, they are different String objects in memory, so == returns false. The correct fix is to use the equals() method (or equalsIgnoreCase() for case-insensitive comparison, but hashes are case-sensitive).

Option A directly fixes the issue. Option B (intern()) is not standard. Option C (compareTo()) could work but equals() is idiomatic.

Option D (hashCode()) compares integers, not strings.

18
MCQhard

What is the result of the following code? Integer a = 100; Integer b = 100; System.out.println(a == b);

A.true
B.false
C.Compilation error
D.Runtime exception
AnswerA

Correct: both refer to same cached Integer object.

Why this answer

Option A is correct because Java caches Integer objects for values between -128 and 127. When autoboxing converts the int literal 100 to an Integer object, both a and b reference the same cached object. Therefore, the == operator, which compares object references, returns true.

Exam trap

Oracle often tests the Integer cache behavior by using values within the cached range (like 100) to trick candidates who assume that == always compares references and would be false for Integer objects.

How to eliminate wrong answers

Option B is wrong because it assumes that == always compares object references for Integer objects, but fails to account for the Integer cache that makes a and b refer to the same object for values in the range -128 to 127. Option C is wrong because the code compiles without error; autoboxing of int to Integer is valid, and the == operator is allowed between two Integer references. Option D is wrong because no runtime exception occurs; the code executes normally and prints the result of the comparison.

19
MCQhard

Given: byte b = 10; b = b + 1; Which statement is true?

A.The value of b becomes 11.
B.b is automatically widened to int then assigned back without error.
C.Compilation error because byte cannot be assigned int.
D.The expression b+1 results in a byte.
AnswerC

b+1 is int, needs explicit cast.

Why this answer

In Java, the expression `b + 1` performs binary numeric promotion, widening the `byte` operand to `int` before addition. The result is an `int` (11), which cannot be implicitly assigned back to a `byte` variable without a cast. Therefore, `b = b + 1;` causes a compilation error: 'incompatible types: possible lossy conversion from int to byte'.

Option C correctly identifies this error.

Exam trap

The trap here is that candidates often forget that arithmetic operations on `byte` (or `short` or `char`) automatically promote the result to `int`, and they mistakenly assume the assignment is valid without a cast.

How to eliminate wrong answers

Option A is wrong because the code does not compile, so the value of `b` never becomes 11. Option B is wrong because while `b` is widened to `int` in the expression, the assignment back to `byte` is not automatic; it requires an explicit cast to avoid a compilation error. Option D is wrong because `b + 1` results in an `int`, not a `byte`, due to Java's binary numeric promotion rules.

20
Multi-Selectmedium

Which two of the following are primitives in Java? (Choose two.)

Select 2 answers
A.byte
B.char
C.String
D.Integer
E.Boolean
AnswersA, B

Correct: byte is a primitive type.

Why this answer

A is correct because `byte` is a primitive data type in Java that stores 8-bit signed integers, ranging from -128 to 127. It is one of the eight primitive types defined in the Java language specification, not an object or reference type.

Exam trap

Oracle often tests the distinction between primitives (lowercase names like `boolean`) and their wrapper classes (capitalized names like `Boolean`), causing candidates to mistakenly select the wrapper class as a primitive.

21
MCQeasy

Given the code snippet: int x = 5; int y = 2; double result = x / y; What is the value of result?

A.2.0
B.Compilation fails
C.2.5
D.2
AnswerA

Correct because integer division yields 2, then cast to double.

Why this answer

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

Exam trap

Oracle often tests the distinction between integer and floating-point division, trapping candidates who forget that dividing two ints in Java always produces an int result, not a double, even when assigned to a double variable.

How to eliminate wrong answers

Option B is wrong because the code compiles successfully; there is no syntax error or type mismatch that would cause compilation to fail. Option C is wrong because it assumes floating-point division occurs, but since both x and y are ints, integer division truncates the result to 2, not 2.5. Option D is wrong because although the integer division yields 2, the assignment to a double variable causes implicit widening conversion to 2.0, not the int value 2.

22
MCQeasy

What is the output of: int i = 1; i = i++; System.out.println(i);

A.Compilation fails
B.0
C.2
D.1
AnswerD

Correct because post-increment returns original.

Why this answer

Option D is correct because in Java, the expression `i = i++` uses the post-increment operator, which first stores the current value of `i` (1) for the assignment, then increments `i` to 2, but the stored original value (1) is then assigned back to `i`. Thus, `i` remains 1, and the output is 1.

Exam trap

The trap here is that candidates often assume `i++` always increments the variable before the assignment, leading them to choose 2, but they miss that the post-increment operator returns the original value for the expression, which is then assigned back.

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; there is no syntax or type error. Option B is wrong because `i` is initialized to 1, and the post-increment does not result in 0; the value 1 is assigned back. Option C is wrong because although `i` is temporarily incremented to 2, the assignment overwrites it with the original value 1, so the final value is not 2.

23
MCQhard

A developer writes: char c = 'A'; int i = c + 1; System.out.println(i); What is the output?

A.66
B.B
C.Compilation error: cannot add char and int.
D.'A1'
AnswerA

'A' is 65, plus 1 equals 66.

Why this answer

In Java, when a `char` is involved in arithmetic with an `int`, the `char` is promoted to its Unicode/ASCII numeric value. 'A' has the ASCII value 65, so `c + 1` becomes 66. The result is an `int`, and `System.out.println(i)` prints the integer 66.

Exam trap

Oracle often tests the misconception that `char` and `int` cannot be added, or that the result remains a `char` and would print as a character, causing candidates to choose 'B' instead of the numeric value.

How to eliminate wrong answers

Option B is wrong because the expression `c + 1` evaluates to an `int`, not a `char`, so it cannot produce the character 'B' without an explicit cast. Option C is wrong because Java allows binary numeric promotion between `char` and `int`, making the addition perfectly valid. Option D is wrong because string concatenation does not occur here; the `+` operator is arithmetic, not string concatenation, and the output is a plain integer, not a string like 'A1'.

24
MCQeasy

Given the code snippet: double d = 10.5; int i = (int) d; System.out.println(i); What is the output?

A.10
B.10.5
C.10
D.Compilation error
AnswerC

Correct truncation result.

Why this answer

Casting a double to int truncates the fractional part, so 10.5 becomes 10.

25
MCQmedium

You are developing a high-frequency trading application where performance is critical. You need to parse and concatenate trade messages. The messages are received as strings and must be combined into a single output string for logging. Each message is appended to the log string. Currently, you are using String concatenation with the '+' operator inside a loop that processes up to 10,000 messages per second. However, performance monitoring shows that the application experiences frequent garbage collection pauses, affecting throughput. Which approach should you take to reduce garbage collection overhead and improve performance?

A.Use StringBuilder instead of String concatenation, ensuring that the StringBuilder is created with an appropriate initial capacity.
B.Use the String.concat() method for each concatenation to reduce object creation.
C.Use StringBuffer instead of String concatenation because it is thread-safe and efficient.
D.Keep using the '+' operator but increase the heap size to reduce garbage collection frequency.
AnswerA

Reduces object creation and GC pressure.

Why this answer

StringBuilder is designed for efficient string concatenation without synchronization overhead. Creating it with an appropriate initial capacity further reduces reallocations. StringBuffer is thread-safe but adds unnecessary overhead in a single-threaded context.

String.concat() still creates new objects. Increasing heap size only delays GC, not reduce object creation.

26
MCQmedium

What is the output of the following? int x = Integer.MAX_VALUE; x++; System.out.println(x);

A.2147483647
B.0
C.Exception
D.-2147483648
AnswerD

Overflow wraps to negative min.

Why this answer

When x is Integer.MAX_VALUE (2147483647) and incremented, integer overflow occurs because Java int uses 32-bit two's complement representation. The value wraps around to the minimum int value, which is -2147483648, making D correct.

Exam trap

The trap here is that candidates often expect an exception or a reset to zero, but Java silently handles integer overflow by wrapping around to the minimum value due to two's complement arithmetic.

How to eliminate wrong answers

Option A is wrong because it assumes no overflow occurs, but incrementing Integer.MAX_VALUE causes overflow. Option B is wrong because overflow does not reset to 0; it wraps to the minimum negative value. Option C is wrong because integer overflow in Java does not throw an exception; it silently wraps around.

27
MCQmedium

A banking application uses a method to calculate interest: double calculateInterest(double balance) { return balance * 0.05; }. The method is called with an int argument: int accountBalance = 1000; double interest = calculateInterest(accountBalance); System.out.println(interest); The output is 50.0, but the expected output is 50.0. However, the developer notices that if the method is changed to return int, the output becomes 50.0 as well. Which statement about implicit casting is true?

A.The double result is implicitly cast to int.
B.The int argument is implicitly cast to double.
C.The code fails to compile because of type mismatch.
D.The multiplication result is automatically rounded.
AnswerB

Correct widening conversion.

Why this answer

Option B is correct because when a method expecting a `double` parameter is called with an `int` argument, Java performs implicit widening primitive conversion (casting) from `int` to `double`. This is safe because `double` can represent all `int` values without loss of precision. The `int` value 1000 is automatically converted to `1000.0` before being used in the calculation.

Exam trap

Oracle often tests the misconception that implicit casting can happen in both directions (widening and narrowing) or that the return type determines the cast direction; the trap here is that candidates may think the `double` result is cast to `int` when the return type changes, but in fact the implicit cast occurs on the argument, not the result.

How to eliminate wrong answers

Option A is wrong because implicit casting from `double` to `int` would require explicit narrowing conversion and would cause a compilation error if attempted implicitly; the result is `double` and remains `double` unless explicitly cast. Option C is wrong because the code compiles successfully due to the implicit widening cast from `int` to `double`. Option D is wrong because the multiplication result is not rounded; it is a precise `double` value (50.0) and the output remains the same when the return type is changed to `int` only because the fractional part is zero.

28
MCQhard

A method has parameters: int x, double y. It performs x += y; and returns x. What is the range behavior?

A.Compilation error: cannot apply += between int and double.
B.Lossy conversion causes runtime exception.
C.Result is truncated to int.
D.x is promoted to double, result is double.
AnswerC

Implicit narrowing cast.

Why this answer

Option C is correct because when the compound assignment operator += is used with an int and a double, the right-hand operand (double) is implicitly narrowed to int via a primitive narrowing conversion. This truncates the fractional part of the double value, and the result is stored as an int. The operation compiles without error and does not throw a runtime exception.

Exam trap

The trap here is that candidates mistakenly believe the result is promoted to double (option D) because they focus on the binary numeric promotion during the addition, forgetting that the compound assignment operator includes an implicit narrowing cast back to the left-hand variable's type.

How to eliminate wrong answers

Option A is wrong because the += operator is defined for mixed numeric types in Java; the compiler does not produce a compilation error for int += double. Option B is wrong because lossy conversion from double to int does not cause a runtime exception; Java performs the narrowing silently with truncation, and no exception is thrown. Option D is wrong because the left-hand operand x is an int variable, so the result of the compound assignment is stored as an int, not a double; the right-hand operand is not promoted to double for the assignment.

29
MCQhard

Refer to the exhibit. Given the code, what is the value printed to the console?

A.19
B.21
C.18
D.20
AnswerC

Correct: Operator precedence and postfix/prefix evaluation yield 18.

Why this answer

The correct answer is 18. The expression is evaluated as: a++ uses the value 10 then increments a to 11; --b decrements b to 4 then uses 4; multiplication has higher precedence, so 4 * 2 = 8; then addition 10 + 8 = 18. Option A is correct.

Option B (19) would result if a++ was after expression (postfix applied later incorrectly). Option C (20) would result if no precedence (10+8 in wrong order). Option D (21) would result if both increments applied beforehand.

30
MCQhard

Given: double d = 5.0; int i = d; What is the result?

A.5.0
B.Compilation fails
C.5
D.Runtime error
AnswerB

Correct because narrowing conversion requires cast.

Why this answer

In Java, assigning a double to an int without an explicit cast causes a compilation error because double is a 64-bit floating-point type and int is a 32-bit integer type. Java does not allow implicit narrowing conversions due to potential loss of precision, so the code fails to compile.

Exam trap

Oracle often tests the distinction between implicit and explicit type conversion, and the trap here is that candidates assume Java will automatically truncate the decimal value (like in some other languages), forgetting that Java requires an explicit cast for narrowing conversions.

How to eliminate wrong answers

Option A is wrong because 5.0 is a double literal, but the code does not compile, so no value is assigned or printed. Option C is wrong because even though 5 is the integer part of 5.0, the assignment is invalid without a cast, so no integer result is produced. Option D is wrong because the error occurs at compile time, not at runtime; Java's type-checking catches the incompatible assignment before execution.

31
MCQmedium

What is the output of the following code? String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2);

A.Hello
B.true
C.Compilation error
D.false
AnswerB

Correct: both refer to the same interned string.

Why this answer

String literals are interned, so both references point to the same object in the string pool, and == compares references, resulting in true.

32
MCQmedium

What is the cause of the compilation error?

A.The value 200 exceeds the range of byte (-128 to 127)
B.The literal 200 is a long
C.The assignment operator is invalid
D.The variable b is not declared
AnswerA

Correct: 200 > 127, so cannot be assigned to byte without cast.

Why this answer

The code attempts to assign the integer literal 200 to a variable of type byte. In Java, the byte data type has a range from -128 to 127. Since 200 exceeds this range, the compiler detects a possible loss of precision and raises a compilation error.

Java does not automatically narrow a larger integer literal to fit into a byte without an explicit cast.

Exam trap

The trap here is that candidates often confuse the range of byte with that of short or int, or mistakenly think the error is due to the literal being a long, when in fact Java treats all unsuffixed integer literals as int.

How to eliminate wrong answers

Option B is wrong because the literal 200 is an int literal by default, not a long; a long literal would require an 'L' suffix (e.g., 200L). Option C is wrong because the assignment operator '=' is perfectly valid for assigning a value to a variable; the error is due to the value's range, not the operator itself. Option D is wrong because the variable 'b' is declared as 'byte b;' in the code, so it is properly declared; the error occurs on the subsequent assignment line.

33
MCQhard

You are part of a team maintaining a legacy order processing system. The system stores order totals as primitive double values. A recent bug report shows that for very large orders (around $1,000,000.00), the total after adding a tax of 8.25% is sometimes off by a few cents. The calculation is: total = orderTotal * (1 + taxRate). The taxRate is defined as double taxRate = 0.0825; The orderTotal is received as a double. The application needs exact monetary precision to two decimal places. Which solution best addresses the precision issue while minimizing changes to the existing code?

A.Use BigDecimal for all monetary calculations, replacing double everywhere.
B.Use DecimalFormat with RoundingMode.HALF_EVEN to format the output.
C.Use Math.round(total * 100) / 100.0 to round to two decimals.
D.Cast the result to float and then back to double to round.
AnswerA

Provides precise decimal arithmetic.

Why this answer

BigDecimal provides exact arithmetic for monetary values. Replacing double with BigDecimal everywhere ensures precision. Math.round with scaling still uses double arithmetic before rounding, which may introduce errors.

DecimalFormat only affects output, not internal calculation. Casting to float loses precision.

34
Multi-Selecteasy

Which two of the following are valid ways to check if two String objects contain the same characters? (Assume s1 and s2 are non-null String references.)

Select 2 answers
A.if (s1.equalsIgnoreCase(s2)) { ... }
B.if (s1 == s2) { ... }
C.if (s1.compareTo(s2) == 0) { ... }
D.if (s1 == s2.intern()) { ... }
E.if (s1.equals(s2)) { ... }
AnswersC, E

compareTo() returns 0 when the strings are lexicographically equal, indicating identical character content.

Why this answer

Options B and C compare the actual character content of the strings. Option A compares references, which is not reliable. Option D ignores case, so it does not check for exact character equality.

Option E uses intern(), which may compare references but is not standard practice.

35
MCQeasy

Which operator is used to compare two values for equality in Java?

A.equals()
B.==
C.!=
D.=
AnswerB

Correct: == is the equality operator for primitives and reference comparison.

Why this answer

Option B is correct because the == operator in Java is used to compare two primitive values for equality, returning true if they are equal. For reference types, == compares object references (memory addresses), not the actual content. This is a fundamental operator defined in the Java Language Specification (JLS §15.21) for equality testing.

Exam trap

Oracle often tests the confusion between the equality operator (==) and the assignment operator (=), as well as the misconception that equals() is an operator rather than a method, tricking candidates who rely on surface-level knowledge of other languages like Python or JavaScript.

How to eliminate wrong answers

Option A is wrong because equals() is a method (not an operator) defined in the Object class, used to compare the logical content of objects (e.g., String content), not primitive values directly; it cannot be used with primitives without autoboxing. Option C is wrong because != is the inequality operator, which checks if two values are not equal, the opposite of what the question asks. Option D is wrong because = is the assignment operator, used to assign a value to a variable, not to compare values; confusing = with == is a common syntax error.

36
MCQmedium

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

A.2.5
B.2.0
C.Compilation fails
D.2
AnswerB

Integer division yields 2, then assigned to double becomes 2.0

Why this answer

Option B 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, a (5) divided by b (2) yields 2, and then the result is implicitly widened to double when assigned to the variable result, producing 2.0.

Exam trap

Oracle often tests the distinction between integer and floating-point division, and the trap here is that candidates mistakenly assume that assigning the result to a double variable will cause the division to be performed in floating-point, when in fact the type of the operands determines the operation, not the target variable.

How to eliminate wrong answers

Option A is wrong because it assumes floating-point division occurs, but integer division truncates the decimal, so 5/2 yields 2, not 2.5. Option C is wrong because the code compiles successfully; there is no syntax or type mismatch error since int divided by int produces an int that is then widened to double. Option D is wrong because although the integer division result is 2, the output is 2.0 due to the double variable storing the value as a floating-point number with a decimal point.

37
Matchingmedium

Match each primitive data type to its default value.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

0

false

0.0d

'\u0000'

0L

Why these pairings

Default values are assigned when fields are not explicitly initialized.

38
MCQmedium

Which keyword is used to declare a constant in Java?

A.constant
B.final
C.static
D.const
AnswerB

Correct. final makes a variable a constant.

Why this answer

The final keyword declares a variable whose value cannot be changed. const and constant are not used.

39
MCQmedium

What is the value of the expression: 2 + 3 * 4 / 2 - 1?

A.9
B.10
C.3
D.7
AnswerD

Correct: following precedence and left-to-right associativity.

Why this answer

Operator precedence: multiplication and division have higher precedence than addition/subtraction, and they are evaluated left-to-right. So 3*4=12, 12/2=6, 2+6=8, 8-1=7.

40
MCQmedium

Refer to the exhibit. What is the output?

A.Runtime exception
B.true
C.Compilation error
D.false
AnswerB

Correct: same object from string pool.

Why this answer

The code uses `==` to compare two `String` objects. In Java, `==` compares object references, not content. Since `s1` and `s2` are created with `new String("true")`, they refer to different objects in memory, so the comparison returns `false`.

However, the question's exhibit likely shows `s1 == s2` where both strings are literals or interned, resulting in `true` due to string interning. Given the correct answer is `true`, the exhibit must use string literals (e.g., `String s1 = "true"; String s2 = "true";`), which are interned and share the same reference.

Exam trap

Oracle often tests the distinction between `==` (reference equality) and `equals()` (value equality) with strings, and the trap here is that candidates assume `==` always compares content, missing the interning behavior of string literals that makes the reference comparison `true`.

How to eliminate wrong answers

Option A is wrong because no runtime exception occurs; comparing two String references with `==` is valid and returns a boolean. Option C is wrong because the code compiles without error; `==` is a legal operator for reference types. Option D is wrong because if the strings are literals, they are interned and refer to the same object, making the comparison `true`, not `false`.

41
MCQeasy

Refer to the exhibit. What is the output?

A.true
B.false
C.Compilation error
D.Java
AnswerB

Correct. str1 and str2 are different objects.

Why this answer

== compares references. str1 is a literal from pool, str2 is a new object, so they are different references.

42
Multi-Selectmedium

Which two expressions evaluate to true? (Choose two)

Select 2 answers
A.true && false
B.10 > 5
C.'a' == 'b'
D.false || !false
E.3 < 3
AnswersB, D

True because 10 is greater than 5.

Why this answer

Option B is correct because the expression `10 > 5` uses the greater-than operator, which evaluates to `true` since 10 is indeed greater than 5. Option D is correct because `!false` evaluates to `true`, and the logical OR operator (`||`) returns `true` if at least one operand is `true`, so `false || true` yields `true`.

Exam trap

Oracle often tests the distinction between relational operators (`<`, `>`) and equality operators (`==`), where candidates mistakenly think `3 < 3` is true or that `'a' == 'b'` might be true due to character comparison confusion.

43
MCQhard

Refer to the exhibit. What is the output?

A.false true false
B.true false true
C.true true true
D.false true true
AnswerD

s1==s2 false, equals true, s1==s3 true

Why this answer

The code uses `String.equals()` to compare the content of strings, which returns `true` for `"Java"` and `"Java"` (first comparison). The second comparison uses `==` to compare string references; since `str1` and `str2` are separate `String` objects created with `new`, they have different memory addresses, so `==` returns `false`. The third comparison uses `String.equals()` again, comparing `"Java"` (a string literal from the pool) with `str2` (a `new String` object), but the content is the same, so it returns `true`.

Thus the output is `false true true`.

Exam trap

Oracle often tests the distinction between `==` (reference equality) and `.equals()` (value equality) for `String` objects, trapping candidates who assume `==` compares string content.

How to eliminate wrong answers

Option A is wrong because it outputs `false true false`, which would require the first comparison to be false (it is true) and the last to be false (it is true). Option B is wrong because it outputs `true false true`, which incorrectly assumes `==` compares content (it compares references, so the second comparison is false, not true). Option C is wrong because it outputs `true true true`, which incorrectly assumes `==` returns true for two different `String` objects created with `new`.

44
MCQeasy

Given: int a = 9; int b = 2; double c = a / b; System.out.println(c); What is the output?

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

Correct. Integer division gives 4, then cast to double implicitly.

Why this answer

Integer division truncates decimal part, so 9/2 = 4, then assigned to double gives 4.0.

45
Multi-Selecthard

Which three statements about String immutability are true? (Choose three)

Select 3 answers
A.String objects can be modified after creation
B.String objects can be changed by calling methods
C.The intern() method returns a String from the pool
D.String concatenation creates a new String
E.StringBuilder can be used to create mutable strings
AnswersC, D, E

True; intern() returns canonical representation.

Why this answer

Option C is correct because the `intern()` method returns a canonical representation of the string from the string pool, ensuring that strings with the same content share the same memory reference, which is a key aspect of immutability and memory optimization in Java.

Exam trap

Oracle often tests the misconception that calling a method on a String changes the original object, when in fact all such methods return a new String, leaving the original unchanged.

46
Multi-Selecteasy

Which TWO of the following are primitive data types in Java?

Select 2 answers
A.String
B.Integer
C.double
D.int
E.Boolean
AnswersC, D

Primitive.

Why this answer

Option C (double) is correct because double is a 64-bit IEEE 754 floating-point primitive data type in Java, used for decimal values with double precision. Option D (int) is correct because int is a 32-bit signed two's complement integer primitive, the default integer type in Java. Both are part of the eight primitive types defined in the Java Language Specification.

Exam trap

Oracle often tests the distinction between primitive types and their corresponding wrapper classes (e.g., int vs. Integer, boolean vs. Boolean), and the trap here is that candidates confuse the capitalized wrapper class name with the lowercase primitive keyword.

47
MCQmedium

Which of the following correctly uses the ternary operator to set int max to the larger of two ints x and y?

A.int max = x > y ? x : y;
B.int max = x > y ? y : x;
C.int max = if (x > y) x else y;
D.int max = (x > y) ? x, y;
AnswerA

Correct syntax.

Why this answer

Ternary: condition ? value_if_true : value_if_false.

48
MCQhard

Given: String s1 = "Hello"; String s2 = "Hello"; String s3 = new String("Hello"); Which of the following is true?

A.s1 == s2 is false, s1 == s3 is true
B.s1 == s2 is true, s1 == s3 is true
C.s1 == s2 is false, s1 == s3 is false
D.s1 == s2 is true, s1 == s3 is false
AnswerD

Correct due to string literal pooling and new String().

Why this answer

Option D is correct because string literals in Java are interned, meaning s1 and s2 both reference the same object from the string pool, so s1 == s2 is true. However, s3 is created using the new keyword, which forces the creation of a new String object on the heap, so s1 == s3 is false because == compares object references, not content.

Exam trap

The trap here is that candidates often confuse == (reference equality) with .equals() (value equality) and assume that all String objects with the same content are the same reference, forgetting that new String() always creates a separate object.

How to eliminate wrong answers

Option A is wrong because it claims s1 == s2 is false, but both are string literals and Java interns them, so they reference the same object. Option B is wrong because it claims s1 == s3 is true, but the new keyword creates a distinct object on the heap, so the references differ. Option C is wrong because it claims s1 == s2 is false, which contradicts string interning behavior.

49
Multi-Selecteasy

Which two of the following are primitive data types in Java? (Choose two)

Select 2 answers
A.boolean
B.double
C.Character
D.String
E.Integer
AnswersA, B

boolean is a primitive type.

Why this answer

Option A is correct because `boolean` is a primitive data type in Java that can hold only two values: `true` or `false`. It is not an object and does not have methods, making it a fundamental building block for conditional logic.

Exam trap

The trap here is that candidates often confuse wrapper classes (like `Integer`, `Character`) with their corresponding primitive types, especially when the wrapper name closely resembles the primitive name (e.g., `Integer` vs `int`).

50
Drag & Dropmedium

Arrange the steps to handle an exception using try-catch-finally in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

The try block contains risky code, catch handles the exception, and finally executes cleanup. The order is try, catch, then finally.

51
MCQmedium

What is the output of the program?

A.false
B.10
C.true
D.20
AnswerA

a > b false, then a == b false.

Why this answer

The program prints 'false' because the `equals()` method is called on a `StringBuilder` object, not a `String`. `StringBuilder` does not override `Object.equals()`, so it uses reference equality. Since `sb1` and `sb2` are distinct objects, `equals()` returns `false`.

Exam trap

Oracle often tests the misconception that `equals()` always compares content, but the trap here is that `StringBuilder` does not override `equals()`, so candidates mistakenly expect `true` based on identical string content.

How to eliminate wrong answers

Option B is wrong because 10 is not printed; the code does not call `System.out.println(10)` or any arithmetic that yields 10. Option C is wrong because `true` would only be printed if `StringBuilder` overrode `equals()` to compare content, which it does not. Option D is wrong because 20 is not printed; the code outputs the boolean result of `sb1.equals(sb2)`, not a numeric value.

52
Drag & Dropmedium

Arrange the steps to create and use a simple Java inheritance hierarchy in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

First create the superclass, then create subclass with extends, override methods if needed, add new members, and then use the subclass.

53
Multi-Selecthard

Which THREE of the following expressions compile without error? (Choose 3)

Select 3 answers
A.byte b = 1 + 2;
B.int i = 5L + 10;
C.double d = 10;
D.boolean b = (false || true);
E.float f = 5.5;
AnswersA, C, D

Compile-time constant, fits byte.

Why this answer

Options A, C, D are correct. A: byte addition promoted to int, then assigned to byte requires explicit cast? Actually byte + byte = int, but assignment to byte will require explicit cast. Wait: byte b = 1+2? 1 and 2 are literals, compile-time constant, so assignment is allowed because constant expression.

Actually 1 and 2 are int literals, but the result is compile-time constant 3, which fits in byte, so it's allowed. So A compiles. B: int + long = long, assigning to int requires explicit cast, so compile error.

C: double d = 10; 10 is int, widening assignment to double is fine. D: boolean b = (false || true); boolean expression, fine. E: float f = 5.5; 5.5 is double by default, requires explicit cast or f suffix, so compile error.

So correct: A, C, D.

54
MCQmedium

Which primitive type can store a single character?

A.String
B.byte
C.short
D.char
AnswerD

Correct.

Why this answer

Option D is correct because the `char` primitive type in Java is specifically designed to store a single 16-bit Unicode character, ranging from '\u0000' (0) to '\uffff' (65535). It is the only primitive type that directly represents a character value, making it the appropriate choice for storing a single character.

Exam trap

Oracle often tests the distinction between primitive types and reference types, and the trap here is that candidates mistakenly choose `String` because they associate it with characters, forgetting that `String` is not a primitive type and is designed for sequences, not single characters.

How to eliminate wrong answers

Option A is wrong because `String` is a reference type (a class in Java), not a primitive type, and it is used to store a sequence of characters, not a single character. Option B is wrong because `byte` is an 8-bit signed integer primitive type that stores numeric values from -128 to 127, not characters. Option C is wrong because `short` is a 16-bit signed integer primitive type that stores numeric values from -32,768 to 32,767, not characters.

55
MCQeasy

Refer to the exhibit. What is the output?

A.false
B.true
C.NullPointerException
D.Compilation error: invalid operator
AnswerB

!a false, b && false false, a || false true.

Why this answer

Option A is correct: Operator precedence: ! highest, then &&, then ||. So !a = false, then b && false = false, then a || false = true. Option B is wrong due to wrong precedence.

Option C and D are wrong.

56
MCQmedium

A junior developer is implementing a method to calculate the average of three exam scores stored as integers. The method should return a double representing the average, rounded to one decimal place. The developer writes: double avg = (score1 + score2 + score3) / 3; However, the result is always an integer. Which of the following modifications ensures the correct result?

A.Cast the sum: double avg = (double)(score1 + score2 + score3) / 3;
B.Change the division to: double avg = (score1 + score2 + score3) / 3.0;
C.Cast each score: double avg = (double)score1 + (double)score2 + (double)score3 / 3;
D.Use BigDecimal: BigDecimal avg = new BigDecimal(score1 + score2 + score3).divide(new BigDecimal(3), 1, RoundingMode.HALF_UP);
AnswerB

Correct: The double literal 3.0 forces floating-point division, preserving the fractional part.

Why this answer

Option A forces floating-point division by using a double literal (3.0), preventing integer truncation. Option B also works but is unnecessary; Option C is overly complex for this task; Option D has operator precedence issues (division before addition).

57
MCQmedium

Given: String s1 = "Java"; String s2 = new String("Java"); What does (s1 == s2) evaluate to?

A.true if interned, false otherwise
B.false
C.true
D.Compilation error
AnswerB

Different objects, == checks references.

Why this answer

Option B is correct: s1 is a literal (interned), s2 is a new object, so == compares references and returns false. Option A is wrong because equals would be true. Option C is wrong because it doesn't compile.

Option D is wrong because they are not the same object.

58
MCQhard

An integer counter variable is incremented in a loop that runs 3 billion times. Initially counter = 0. After the loop, the value is printed. Which code snippet correctly handles potential overflow?

A.int counter = 0; for(int i=0; i<3000000000L; i++) counter++; System.out.println(counter);
B.int counter = 0; for(int i=0; i<3000000000L; i++) counter += 1; System.out.println(counter);
C.int counter = 0; for(int i=0; i<3000000000L; i++) counter = Math.addExact(counter, 1); System.out.println(counter);
D.long counter = 0; for(long i=0; i<3000000000L; i++) counter++; System.out.println(counter);
AnswerD

long can hold 3e9 without overflow.

Why this answer

Option D uses a long variable, which can hold the value up to 9e18, avoiding overflow. Options A and C use int and will overflow because 3e9 exceeds Integer.MAX_VALUE (2.147e9). Option B throws an ArithmeticException on overflow, which is not handling overflow gracefully.

59
MCQmedium

What is the result of the following code snippet? int a = 5; int b = 2; double c = (double) (a / b); System.out.println(c);

A.2
B.2.0
C.Compilation error
D.2.5
AnswerB

a/b is integer division (2), then cast to double.

Why this answer

Option B is correct because the expression `(a / b)` performs integer division, resulting in 2 (since both a and b are ints). The cast `(double)` is applied to the result of that integer division, converting the integer 2 to 2.0. The output is therefore 2.0.

Exam trap

The trap here is that candidates often believe the cast to double will cause the division to be performed in floating-point, but the cast is applied after the integer division, so the fractional part is already lost.

How to eliminate wrong answers

Option A is wrong because it omits the decimal point; the cast to double ensures the output is a floating-point number, not an integer. Option C is wrong because the code compiles without error; the cast is syntactically valid and applied to an int expression. Option D is wrong because it assumes the division is performed in floating-point context, but integer division truncates the fractional part before the cast, so the result is 2.0, not 2.5.

60
MCQhard

What is the result of the following code? int a = 8; int b = 3; System.out.println(a >> 1);

A.2
B.3
C.4
D.16
AnswerC

8 shifted right by 1 is 4.

Why this answer

The right shift operator `>>` shifts the bits of the integer `a` (which is 8, binary `1000`) to the right by 1 position. This discards the least significant bit and fills the most significant bit with the sign bit (0 for positive numbers), resulting in binary `0100`, which is decimal 4. Therefore, `System.out.println(a >> 1)` prints 4.

Exam trap

Oracle often tests the confusion between the right shift (`>>`) and left shift (`<<`) operators, as well as the misconception that `>> 1` always divides by 2 (which is true for positive integers but not for negative ones due to sign extension).

How to eliminate wrong answers

Option A is wrong because 2 would be the result of `a >> 2` (shifting right by 2 positions), not `a >> 1`. Option B is wrong because 3 would be the result of `a % b` (modulus) or `a / b` with integer division (8/3 = 2, not 3), not a right shift. Option D is wrong because 16 would be the result of `a << 1` (left shift, which multiplies by 2), not a right shift.

61
MCQhard

What is the value of z after executing: int x = 3; int y = 2; int z = x++ * --y;

A.3
B.6
C.4
D.2
AnswerA

x++ uses 3, --y yields 1, product = 3.

Why this answer

The expression `x++ * --y` uses post-increment on `x` and pre-decrement on `y`. Post-increment returns the original value of `x` (3) before incrementing it to 4. Pre-decrement decrements `y` from 2 to 1, then returns the new value (1).

The multiplication is 3 * 1 = 3, which is assigned to `z`. So the correct answer is 3.

Exam trap

Oracle often tests the difference between pre- and post-increment/decrement operators, and the trap here is that candidates mistakenly apply both operators to the original values or forget that post-increment returns the value before the increment.

How to eliminate wrong answers

Option B (6) is wrong because it assumes both operators use the original values (3 * 2) without considering that `--y` decrements before use. Option C (4) is wrong because it might result from misapplying post-increment on `x` (using 4) and pre-decrement on `y` (using 1), or from thinking `x++` returns the incremented value. Option D (2) is wrong because it could come from incorrectly applying pre-decrement to `y` (1) and then multiplying by 2, or from confusing the order of operations.

62
Multi-Selecteasy

Which two of the following operators are logical operators in Java? (Choose two.)

Select 2 answers
A.||
B.&
C.&&
D.|
E.~
AnswersA, C

Correct: || is the logical OR operator.

Why this answer

Option A is correct because || is the logical OR operator in Java, which returns true if at least one of the two boolean operands is true. Option C is correct because && is the logical AND operator, which returns true only if both boolean operands are true. Both operators perform short-circuit evaluation, meaning the right operand is not evaluated if the result is already determined by the left operand.

Exam trap

The trap here is that candidates often confuse bitwise operators (&, |) with logical operators (&&, ||) because they look similar, but Java treats them distinctly based on operand types and evaluation behavior.

63
MCQhard

A developer is writing a bitmask validation method. The method should return true if both input integers (x and y) have exactly the same least significant bit set. The developer writes: if (x & y == 1) { return true; } However, the condition never evaluates to true even when both numbers are odd (least significant bit = 1). Debugging shows that x and y are positive integers. What is the root cause and the correct fix?

A.Use modulo: if (x % 2 == 1 && y % 2 == 1) { ... }
B.Add parentheses: if ((x & y) == 1) { ... }
C.Use bitwise OR: if (x | y == 1) { ... }
D.Use logical AND: if (x && y == 1) { ... }
AnswerB

Parentheses ensure the bitwise AND is performed before the comparison, correctly checking if the least significant bit of x & y is 1.

Why this answer

In Java, the bitwise AND operator & has lower precedence than the equality operator ==. Therefore, x & y == 1 is parsed as x & (y == 1), which performs a boolean comparison (y == 1) and then bitwise ANDs x with the boolean result (true = 1, false = 0), not what was intended. The fix is to add parentheses: (x & y) == 1.

Option A corrects the precedence. Option B uses logical AND (&&) which is not bitwise. Option C uses bitwise OR (|) which is not correct for checking both bits set.

Option D uses modulo (%), which works for odd check but not for bitmasking in general.

64
MCQeasy

A junior developer wrote the following code to compare two strings entered by a user: if (username == "admin") { grantAccess(); } else { denyAccess(); }. The code always denies access even when the user enters 'admin'. What is the most likely cause, and how should the code be fixed?

A.The input string has leading or trailing spaces. Use username.trim().equals("admin") instead.
B.The variable username is null, causing a NullPointerException that is caught and denied access. Add a null check.
C.The strings are compared using == which is case-sensitive. Use username.equalsIgnoreCase("admin") instead.
D.The strings are compared using == which checks reference equality. Use username.equals("admin") instead.
AnswerD

equals compares content.

Why this answer

The == operator compares object references, not content. String literals may be interned, but dynamically entered strings are not guaranteed to be interned. The correct fix is to use equals() method.

65
MCQhard

Given: String str = "Java"; str = str.concat(" SE"); str.replace('a', 'A'); System.out.println(str); What is the output?

A.Java
B.JAVA SE
C.Java SE
D.JAvA SE
AnswerC

Correct because replace result is ignored.

Why this answer

Option C is correct because the `concat` method returns a new String "Java SE" which is assigned back to `str`. The `replace` method also returns a new String but its result is not assigned to any variable, so the original `str` remains unchanged. The final `println` outputs the current value of `str`, which is "Java SE".

Exam trap

The trap here is that candidates assume `replace` modifies the original string in place, forgetting that String methods return a new object and the result must be assigned to affect the variable.

How to eliminate wrong answers

Option A is wrong because `str.concat(" SE")` creates a new String "Java SE" and assigns it to `str`, so the output is not just "Java". Option B is wrong because `replace('a', 'A')` is not applied to `str` (its return value is discarded), so the string is not converted to "JAVA SE". Option D is wrong because the `replace` method would replace all occurrences of 'a' with 'A', but since its result is not stored, `str` remains "Java SE", not "JAvA SE".

66
MCQhard

Given boolean a = true, b = false, c = true; What is the result of (a || b) && (b || c)?

A.Short-circuit evaluation prevents evaluation
B.true
C.Compilation error
D.false
AnswerB

Both sides evaluate to true.

Why this answer

a||b = true, b||c = true, true && true = true.

67
Multi-Selectmedium

Which three of the following code snippets produce the output '5'?

Select 3 answers
A.System.out.println(2 + "3");
B.System.out.println(2 + 3);
C.System.out.println("5");
D.System.out.println("2" + 3);
E.System.out.println(5);
AnswersB, C, E

Prints 5 as int.

Why this answer

Option B is correct because the expression `2 + 3` performs integer addition, resulting in `5`, which is then passed to `System.out.println` and printed as the string representation of the integer `5`. Option C is correct because the string literal `"5"` is printed directly. Option E is correct because the integer literal `5` is printed as its string representation.

Exam trap

The trap here is that candidates often forget that `+` with a `String` operand triggers concatenation, not arithmetic, leading them to incorrectly select options A or D as producing `5`.

68
MCQeasy

Which primitive type can store a single character?

A.String
B.char
C.int
D.Character
AnswerB

Primitive type for characters.

Why this answer

char is the primitive for a single 16-bit Unicode character.

69
MCQmedium

A developer wants to compare two String objects for content equality. Which code snippet will work correctly?

A.str1.compareTo(str2) == 0
B.Both B and C are correct
C.str1.equals(str2)
D.str1 == str2
AnswerB

Both equals() and compareTo() (with ==0) compare content.

Why this answer

Option B is correct because both `str1.compareTo(str2) == 0` and `str1.equals(str2)` correctly compare the content of two String objects for equality. The `compareTo` method returns 0 when the strings are lexicographically equal, and `equals` returns true when the contents match. Option D (`==`) compares object references, not content, so it is incorrect.

Exam trap

Oracle often tests the distinction between reference equality (`==`) and content equality (`equals`), and the trap here is that candidates may think `compareTo` is only for ordering, not equality, or that `==` works for strings because of interning, but it fails for non-interned strings.

How to eliminate wrong answers

Option A is wrong because `compareTo` returns 0 for equal strings, but it is not the only correct way; however, the question asks which snippet will work correctly, and both A and C do, so the correct answer is 'Both B and C are correct' (Option B). Option C is correct because `equals` compares content. Option D is wrong because `==` compares object references, not string content, and will return false for two different String objects with the same characters.

70
Multi-Selecteasy

Which TWO of the following are valid Java identifiers? (Choose 2)

Select 2 answers
A.$value
B.my#var
C.my-var
D._myVar
E.2ndPlace
AnswersA, D

Valid: starts with $.

Why this answer

Option A ($value) is correct because Java allows identifiers to begin with a dollar sign ($) or underscore (_), and the rest can include letters, digits, or these special characters. The dollar sign is a valid starting character per the Java Language Specification (JLS §3.8), so $value is a legal identifier.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit and cannot contain special characters like # or -, but candidates may mistakenly think hyphens or hash symbols are allowed because they appear in other programming contexts or variable naming conventions.

71
MCQmedium

A developer needs to build a SQL query string by concatenating many parts. Which approach is most efficient for repeated concatenation?

A.Using StringBuffer.append()
B.Using StringBuilder.append()
C.Using String concatenation with +=
D.Using StringBuilder.append()
AnswerB

Efficient and non-synchronized.

Why this answer

StringBuilder.append() is efficient for many concatenations as it uses a mutable buffer. StringBuffer is synchronized and slower. String concatenation with '+' creates many intermediate objects.

String.concat() also creates new objects.

72
MCQhard

Given: int a = 10; int b = 20; boolean flag = a++ > 10 && ++b > 20; What are the values of a and b after execution?

A.a=10, b=21
B.a=10, b=20
C.a=11, b=21
D.a=11, b=20
AnswerD

Correct: a becomes 11, b remains 20 because the right side of && is not evaluated.

Why this answer

The expression `a++ > 10 && ++b > 20` uses short-circuit evaluation. Since `a++` is post-increment, the comparison uses the original value of `a` (10) before incrementing, so `10 > 10` is false. Because the left operand is false, the `&&` operator short-circuits and the right operand `++b > 20` is never evaluated.

Therefore, `a` is incremented to 11, but `b` remains 20, making option D correct.

Exam trap

The trap here is that candidates often forget that post-increment `a++` uses the original value for the comparison but still increments `a` afterward, and they also overlook short-circuit evaluation, assuming both sides of `&&` are always evaluated.

How to eliminate wrong answers

Option A is wrong because it incorrectly assumes `a` remains 10, but post-increment `a++` always increments `a` after the comparison, so `a` becomes 11. Option B is wrong because it assumes both `a` and `b` are unchanged, but `a` is incremented to 11. Option C is wrong because it assumes the right operand `++b` is evaluated, which would make `b` 21, but short-circuit evaluation prevents this since the left operand is false.

Page 1 of 2 · 112 questions totalNext →

Ready to test yourself?

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