Courseiva

CCNA Primitives, Strings and Operators Questions

74 of 105 questions · Page 1/2 · Primitives, Strings and Operators · 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

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

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 D are valid
B.float f = 10.5f;
C.float f = 10.5;
D.float f = 10.5F;
AnswerA

This option claims both B and C are valid, but C is invalid, so A is incorrect.

Why this answer

Options B and D are valid because they use the f or F suffix to explicitly denote a float literal. Option C is invalid because 10.5 is a double literal and cannot be implicitly converted to float without a cast or suffix.

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

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

The exhibit's code attempts an integer division where the divisor evaluates to zero during execution. Java's runtime environment detects this illegal operation, leading to an `ArithmeticException`. This specific exception is a subclass of `RuntimeException`, which is unchecked and typically indicates a programming error that occurs after compilation, preventing the program from continuing its normal flow.

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

The correct answers are B, D, and E.

B is correct: Implicit widening conversion from int to long is allowed because long has a larger range (64-bit vs 32-bit).

D is correct: A char can be assigned to an int without a cast because char is 16-bit unsigned and int is 32-bit, so the value fits without loss.

E is correct: Narrowing conversion from double to int requires an explicit cast because double has a larger range and fractional part cannot be automatically discarded.

A is false: A float cannot be implicitly converted to long because float is 32-bit floating-point; conversion would lose precision and requires an explicit cast.

C is false: A boolean cannot be converted to any numeric type, even with casting; boolean and numeric types are incompatible.

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

The correct answers are C and E. Option C is true because String objects in Java are immutable; once created, they cannot be changed. Option E is true because the intern() method places the string into the string pool if it is not already present, allowing reuse of string literals.

Option A is false: String is immutable regardless of whether it is created with new or a literal. Option B is false: String does not implement Cloneable; it implements Serializable, Comparable, and CharSequence. Option D is false: methods like toUpperCase() return a new String object and do not modify the original.

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 and throws an ArithmeticException if the result overflows, exactly meeting the requirement to detect overflow and throw an exception without changing data types. Option A (bitwise AND) does not detect overflow reliably. Option C (casting to long) changes the data type, violating the legacy constraint.

Option D (BigInteger) also changes the data type. Therefore, option B is correct.

11
MCQhard

What is the output of the following code? int x = 5; int y = 16; System.out.print(x + "," + y);

A.5,16
B.4,16
C.4,12
D.5,12
AnswerA

As explained.

Why this answer

The code initializes `int x = 5;` and `int y = 16;` and then prints them using `System.out.print(x + "," + y);`. Since there are no operations that change the values, the output is simply the initial values: 5,16. Therefore, option A is correct.

Exam trap

This question tests simple variable initialization and output. The trap is that candidates might overthink and assume some operation changes the values, but since no operations are present, the output is simply the initial values. The comma in System.out.print is just a string literal, not a separator for multiple arguments.

How to eliminate wrong answers

Option B is wrong because it incorrectly assumes both operations are pre-increment/pre-decrement (resulting in 6+15=21, then x=6,y=15) or misapplies the order. Option C is wrong because it suggests the post-increment on x yields 4 (which would require pre-decrement on x, not post-increment) and the pre-decrement on y yields 12 (which would require an extra decrement). Option D is wrong because it correctly gets the first number as 5 but incorrectly computes the second number as 12, likely by applying the decrement twice or misreading the output order.

12
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

`double` is a primitive floating-point data type, making it suitable for representing decimal numbers like currency values. Its 64-bit precision allows for storing fractional parts, directly addressing the requirement for two decimal places. Among the available primitive types, `double` offers the best balance of range and precision for general-purpose decimal arithmetic, making it the most appropriate choice when a primitive type is specified for currency representation.

Why this answer

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

13
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

The correct matches are: javac compiles source code, java runs applications, javadoc generates documentation, and jar creates archives. Common confusions involve mixing up javac with jar and java with javadoc.

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

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

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

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

18
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

This directly fixes the issue.

Why this answer

The == operator in Java compares object references, not string content. Even if two hash strings are logically identical, they are distinct String objects, so == returns false. Option A (equals()) is the correct and idiomatic fix because equals() compares the actual content.

Option B (hashCode()) is incorrect because hash codes can collide (different strings can have the same hash code), and passwords require exact string equality. Option C (intern()) would allow == to work after interning, but it is unnecessary and not recommended for password validation due to the permanent string pool and performance overhead. Option D (compareTo()) would also return 0 for equal strings, but equals() is the standard method for equality checks.

19
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

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.

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

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

22
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

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.

23
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

The post-increment operator `i++` first retrieves the current value of `i` (which is 1) for use in the assignment expression. Subsequently, `i` is incremented to 2. However, the assignment `i = ...` then takes the *original* value (1) and assigns it back to `i`, effectively overwriting the incremented value. This specific order of operations, where the assignment occurs *after* the value is retrieved but *before* the incremented value can persist, ensures `i` remains 1 when printed.

Why this answer

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.

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

25
MCQeasy

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

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

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

Why this answer

Casting a double to int truncates the fractional part, so 10.5 becomes 10. Option A (10.0) is incorrect because the result is an int without decimals; Option B is the original value; Option D is incorrect because the code compiles and runs.

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

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

28
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

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.

29
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

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.

30
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

The value 18 is printed because Java's operator precedence rules are correctly applied to the arithmetic expression. Multiplication operations are performed before addition. Therefore, if the code involved an expression like `5 + 2 * 6 + 1`, `2 * 6` would evaluate to `12` first. Subsequently, the additions `5 + 12 + 1` are executed from left to right, resulting in `17 + 1`, which yields the final value of 18. This satisfies the constraint of correctly evaluating expressions based on operator hierarchy.

Why this answer

18 (option C). The expression `a++ + --b * 2` is evaluated according to Java operator precedence: postfix increment (`a++`) uses the current value of `a` (10) then increments `a` to 11; prefix decrement (`--b`) decrements `b` from 5 to 4 then uses 4; multiplication has higher precedence than addition, so `--b * 2` computes 4 * 2 = 8; then addition: 10 + 8 = 18. Option A (19) would result if the postfix increment had been applied before the rest of the expression (i.e., using 11 instead of 10).

Option B (21) would result if both increments were applied before evaluation (a becomes 11, b becomes 4, and then 11 + 4 * 2 = 11 + 8 = 19, not 21; actually 21 is far off). Option D (20) would result if addition were performed before multiplication (10 + 4 = 14, then 14 * 2 = 28, not 20; 20 is not directly derivable). Thus only step-by-step evaluation yields 18.

31
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

Compilation fails because Java does not permit implicit narrowing primitive conversions. Assigning a `double` value to an `int` variable without an explicit cast is a narrowing conversion, as `double` has a larger range and precision than `int`. Java's type system requires an explicit cast, such as `int i = (int) d;`, to acknowledge the potential loss of data or precision during such a conversion.

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.

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

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

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

35
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

The correct ways to compare two String objects for character equality are using the equals() method (option E) or compareTo() method returning 0 (option C). Option A (equalsIgnoreCase) ignores case, so it would treat strings with different cases as equal. Option B (==) compares object references, not content.

Option D compares s1 with the interned version of s2; this only works if s1 is also interned, which is not guaranteed, making it unreliable.

36
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

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.

37
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 in Java truncates the fractional part, so `a / b` computes `5 / 2 = 2` as an `int`. The result is then implicitly widened to `double` during assignment, yielding `2.0`. This satisfies the constraint that both operands are `int`, causing the division operator to perform integer arithmetic before the widening conversion.

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

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 created with string literals (e.g., `String s1 = "true"; String s2 = "true";`). In Java, string literals are interned, meaning they refer to the same object in the string pool. Therefore, the reference comparison returns `true`.

The `==` operator checks reference equality, not content equality, but due to interning, the references are the same. If `new String("true")` were used, the comparison would be `false` because different objects are created.

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

What is the output of the following code? String str1 = "Java"; String str2 = new String("Java"); System.out.println(str1 == str2);

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

Correct. str1 and str2 are different objects.

Why this answer

The == operator compares object references. One string is a literal (stored in the string pool) and the other is created using the 'new' keyword (heap object). They are different references, so the comparison returns false.

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

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
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.0.0
D.4
AnswerB

In integer division, 9/2 = 4, and since c is double, it becomes 4.0. This is correct.

Why this answer

The expression `a / b` performs integer division because both operands are `int`. The result of `9 / 2` is `4` (the fractional part is truncated). This integer result is then implicitly widened to `double` when assigned to `c`, producing `4.0`.

Therefore, the output is `4.0`.

Exam trap

Oracle often tests the distinction between integer and floating-point division, trapping candidates who assume that assigning the result to a `double` variable automatically performs floating-point division.

How to eliminate wrong answers

Option A is wrong because it assumes floating-point division occurs, yielding `4.5`, but integer division truncates the fractional part. Option C is wrong because it is a duplicate of the correct answer but listed as a separate option; the output is `4.0`, not `4.0` as a distinct choice. Option D is wrong because it outputs `4` as an integer, but the variable `c` is of type `double`, so the printed value includes the decimal point and zero.

44
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

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.

45
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

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

46
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

The ternary operator `? :` evaluates the boolean expression `x > y`; if true, it returns `x`, otherwise `y`, assigning the larger value to `int max`. This is the standard syntax for a conditional assignment in Java, as defined in the Java Language Specification (JLS §15.25).

Exam trap

Oracle often tests the exact syntax of the ternary operator, specifically that the colon `:` is required to separate the true and false expressions, and that the operator returns a value, not a statement like `if`.

How to eliminate wrong answers

Option B is wrong because it assigns the smaller value (`y` when `x > y` is true, and `x` when false), effectively setting `max` to the minimum of the two ints, not the maximum. Option C is wrong because it uses `if` statement syntax inside an expression, which is not valid in Java; the ternary operator requires the `? :` syntax, not an `if-else` block. Option D is wrong because it uses a comma `,` instead of a colon `:` to separate the two possible values, which is syntactically incorrect and will cause a compilation error.

47
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

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.

48
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

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

49
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

50
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
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

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

52
MCQmedium

Which primitive type can store a single character?

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

Correct.

Why this answer

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.

53
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

The expression evaluates to true. Operator precedence: ! highest, then &&, then ||. Given typical values (a=false, b=true), !a=true, then b && !a = true && true = true, then a || (b && !a) = false || true = true.

Thus output is true. Option A is incorrect because the expression yields true, not false. Option C and D are incorrect as there is no exception or compilation error.

54
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

S1 is a string literal which is interned, while s2 is created using the 'new' keyword, resulting in a different object in heap memory. The '==' operator compares object references, so it returns false. Option A is incorrect because 'true if interned' is misleading; s1 is interned, but the comparison is false because s2 is a separate object.

Option C ('true') is wrong because references differ. Option D ('Compilation error') is incorrect; the code compiles and runs without error.

55
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

Uses a long variable, which can hold the value up to 9e18, avoiding overflow. Options A and B use int and will silently overflow because 3e9 exceeds Integer.MAX_VALUE (2.147e9). Option C uses Math.addExact, which throws an ArithmeticException on overflow; while this detects overflow, the question asks for handling it gracefully, and using a long is the proper approach.

56
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

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.

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

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

59
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

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

60
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 ==. So x & y == 1 is parsed as x & (y == 1), which first evaluates y == 1 to a boolean, then performs bitwise AND with x, treating true as 1 and false as 0. That's not the intended check.

The correct fix is to add parentheses to ensure & is evaluated first: (x & y) == 1. This checks if both numbers have the same least significant bit set (both odd). Option B correctly adds parentheses.

Options A, C, and D do not correctly address the bitwise check: A uses modulo which works for odd/even but not general bitmasking; C uses bitwise OR which checks if either bit is set; D uses logical AND which is for booleans, not integers.

61
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

In Java, the == operator compares object references, not the actual content of strings. When comparing two String objects for logical equality, the .equals() method must be used. The code if (username == "admin") checks whether username and the string literal "admin" refer to the same memory location, which is false when username is obtained from user input (e.g., via Scanner or console), even if the characters are identical.

Exam trap

Oracle Java Foundations exam often tests the distinction between reference equality (==) and value equality (.equals()) for String objects, and the trap here is that candidates may think the issue is case sensitivity or whitespace, when the fundamental problem is the use of the wrong comparison operator.

How to eliminate wrong answers

Option A is wrong because while leading/trailing spaces could cause a mismatch, the most likely cause is the use of ==, not spaces; trimming alone does not fix the reference comparison issue. Option B is wrong because a null username would throw a NullPointerException at runtime, not silently deny access, and the code does not show any exception handling. Option C is wrong because case sensitivity is not the core issue; the problem is reference equality, and using equalsIgnoreCase would still fail if == is used (the method would not be called correctly).

62
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

The output is "Java SE" because Java String objects are immutable. The `str.concat(" SE")` operation creates a new String "Java SE" and successfully reassigns `str` to refer to this new object. However, `str.replace('a', 'A')` also creates a new String ("JAvA SE"), but its return value is not assigned back to `str`. Consequently, `str` continues to refer to the "Java SE" object established by the `concat` method, which is then printed to the console.

Why this answer

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

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

64
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

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

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

66
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

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

67
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 String.concat()
AnswerB

StringBuilder.append() uses a mutable buffer without synchronization, making it the most efficient for repeated concatenation.

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.

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

69
Multi-Selecthard

Which THREE of the following are valid Java operators?

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

Shift operator.

Why this answer

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

Exam trap

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

70
MCQmedium

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

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

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

Why this answer

The expression `i++ + ++i` is evaluated as follows: First, `i++` uses the current value of i (1) and then increments i to 2. Then, `++i` increments i from 2 to 3 and uses the new value (3). So, j = 1 + 3 = 4.

Option A (3) incorrectly assumes both operations use the same initial value. Option B (5) incorrectly increments both times before using. Option C (2) incorrectly uses post-increment for both.

71
MCQeasy

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

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

Integer division yields 4, stored as double.

Why this answer

(4.0). In Java, when dividing two integers, the result is integer division, which truncates the fractional part. So 9 / 2 yields 4 (int).

This int value is then assigned to a double variable, resulting in 4.0. Option A (4) would be the result of printing an int, but since result is double, it prints 4.0. Option C is incorrect because the code compiles fine.

Option D is incorrect because 4.5 would require at least one operand to be double (e.g., a / (double)b).

72
MCQeasy

Given: int x = 10; int y = 20; What is the output of System.out.println(x + y * 2);?

A.40
B.60
C.30
D.50
AnswerD

Correct: due to operator precedence.

Why this answer

Multiplication has higher precedence than addition: y * 2 = 40, then x + 40 = 50.

73
MCQhard

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

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

Strings in Java are indeed immutable. This means that once a `String` object has been initialised, its sequence of characters cannot be altered. Any operation that appears to modify a string, such as concatenation or substring extraction, actually results in the creation of a *new* `String` object containing the modified value, whilst the original `String` object remains unchanged in memory. This characteristic makes the statement true regarding the `String` class.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

74
Multi-Selectmedium

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

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

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

Why this answer

Options A and B are correct. The long data type is 64-bit with a range from -2^63 to 2^63-1. The short data type is 16-bit with a range from -32,768 to 32,767.

Option C is false because the float data type is 32-bit and cannot represent decimal numbers precisely; it is an approximate type. Option D is false because the boolean data type's size is not strictly defined; it is typically represented as a byte or word, not a single bit. Option E is false because the char data type stores Unicode characters (16-bit) and can represent a wide range of characters beyond ASCII.

Page 1 of 2 · 105 questions totalNext →

Ready to test yourself?

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