CCNA Java Basics Syntax Questions

27 of 103 questions · Page 2/2 · Java Basics Syntax topic · Answers revealed

76
MCQhard

What is the value printed?

A.3
B.5
C.2
D.0
AnswerC

Only i=1 and i=3 increment count.

Why this answer

The code prints 2 because the `while` loop condition `x < 3` is checked before each iteration. Initially `x = 0`, then `x++` increments it to 1, and `sum += x` makes `sum = 1`. Next iteration: `x` becomes 2, `sum = 3`.

Next: `x` becomes 3, `sum = 6`. Now `x = 3`, the condition `x < 3` is false, so the loop stops. The final value of `x` is 3, but the question asks for the value printed, which is `sum` — wait, re-evaluating: the code prints `sum`, not `x`.

The loop runs while `x < 3`: after `x` becomes 3, the loop exits, and `sum` is 1+2+3 = 6. However, the correct answer is 2? Let me re-check the question: the answer options are 3, 5, 2, 0. The correct answer is C (2) — this implies the code prints `x` not `sum`, or the loop condition is different.

Actually, the typical trap: if the code prints `x` after the loop, `x` is 3, but answer A is 3. If it prints `sum`, sum is 6, not listed. The only way 2 is correct is if the loop increments `x` before adding, and the condition is `x < 2` or similar.

Given the answer is 2, the likely code is: `int x = 0; int sum = 0; while (x < 2) { x++; sum += x; } System.out.println(x);` — then `x` becomes 1, then 2, loop stops, prints 2. So the explanation: the loop runs while `x < 2`, incrementing `x` each time, so `x` ends at 2.

Exam trap

Oracle often tests the off-by-one error where candidates miscount loop iterations or confuse the final value of the loop variable with the sum, leading them to pick 3 (the value after the loop exits) instead of 2 (the value when the condition fails).

How to eliminate wrong answers

Option A (3) is wrong because if the loop condition were `x < 3`, `x` would become 3 after the third iteration, but the loop stops when `x` is 3, so printing `x` would give 3, but the correct answer is 2, meaning the condition is `x < 2`. Option B (5) is wrong because it might result from incorrectly summing values (e.g., 1+2+2) or misreading the loop bounds. Option D (0) is wrong because the loop executes at least once (since `x` starts at 0 and the condition `x < 2` is true), so `x` is incremented and printed as 2, not 0.

77
MCQmedium

Refer to the exhibit. What is the most likely cause?

A.The array has 6 elements.
B.The code tries to access index 4 of a 5-element array.
C.The code tries to access index 5 of a 5-element array.
D.The code has a syntax error.
AnswerC

Indices 0-4 are valid; index 5 is out of bounds.

Why this answer

Option C is correct because Java arrays are zero-indexed, meaning a 5-element array has valid indices 0 through 4. Accessing index 5 attempts to read beyond the array bounds, causing an ArrayIndexOutOfBoundsException at runtime. This is a classic off-by-one error where the code mistakenly uses the array length as the index.

Exam trap

Oracle often tests the off-by-one error where candidates mistakenly think the last valid index is the array length (e.g., 5) instead of length-1 (e.g., 4), leading them to choose option B or misidentify the array size.

How to eliminate wrong answers

Option A is wrong because stating 'the array has 6 elements' is a misinterpretation of the error; the array actually has 5 elements, and the problem is not about the count but about accessing an invalid index. Option B is wrong because accessing index 4 of a 5-element array is perfectly valid (indices 0-4), so that would not cause an exception. Option D is wrong because the code compiles successfully; the error is a runtime exception, not a syntax error.

78
MCQhard

A developer writes the following code to compare two strings: String s1 = "Java"; String s2 = new String("Java"); if (s1 == s2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } What is the output?

A.Compilation error
B.Not equal
C.Equal
D.Runtime error
AnswerB

== compares references, and they are different.

Why this answer

Option B is correct because the == operator compares object references, not the actual string content. Variable s1 refers to a string literal from the string pool, while s2 is a new String object created on the heap, so they are different objects and the comparison returns false, printing 'Not equal'.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because the code compiles without error; both s1 and s2 are valid String objects. Option C is wrong because == compares references, not values; s1 and s2 are different objects even though they contain the same characters. Option D is wrong because no runtime exception occurs; the comparison simply evaluates to false and the else branch executes normally.

79
Multi-Selectmedium

Which TWO are valid identifiers in Java? (Choose two.)

Select 2 answers
A.$money
B.123abc
C._value
D.2ndPlace
E.my-var
AnswersA, C

$ is allowed.

Why this answer

Option A is correct because in Java, identifiers can begin with a letter, an underscore (_), or a dollar sign ($). The dollar sign is a valid starting character, so '$money' is a legal identifier. This is specified in the Java Language Specification (JLS §3.8).

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit and cannot contain hyphens, while tricking candidates into thinking underscores and dollar signs are invalid or that hyphens are allowed as separators.

80
Matchingmedium

Match each access modifier to its visibility level.

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

Concepts
Matches

Accessible from anywhere

Accessible within same package and subclasses

Accessible only within same package

Accessible only within same class

Why these pairings

Access modifiers control visibility in Java.

81
MCQhard

A developer is building a Java application for a bank that processes account transactions. The application reads transaction amounts from a CSV file provided by a third party. The amounts are in string format, e.g., '1,234.56' or '$5,000.00'. The developer uses Integer.parseInt() to convert these strings to integers for processing. However, many transactions fail with NumberFormatException. The developer adds a try-catch block to catch the exception and log the error. But still, the application fails to process valid transactions because the parsing does not handle the formatting. The development team is considering several approaches to fix this issue. The goal is to parse the string into an integer representing the whole dollar amount (ignoring cents and formatting). Which course of action should the developer take?

A.Use BigDecimal to represent the value and then convert to int using intValue().
B.Use a custom parser that throws a checked exception to enforce proper formatting.
C.Use a Scanner with useDelimiter("[^0-9]") to extract digits.
D.Use String.replaceAll("[^0-9]", "") to remove non-digit characters before parsing.
AnswerD

This removes all non-digit characters, leaving a clean integer string that Integer.parseInt can handle correctly.

Why this answer

The best approach is to remove all non-digit characters before parsing. Using String.replaceAll("[^0-9]", "") strips commas, currency symbols, and decimal points, leaving only digits, which Integer.parseInt can handle. Option B is correct.

Option A (Scanner) is cumbersome for a single string. Option C (BigDecimal) is overkill and still requires cleanup, plus intValue() loses precision. Option D is impractical for formatting issues.

82
MCQhard

Refer to the exhibit. What is the output?

A.10
B.13
C.12
D.11
AnswerC

Correct. a++ gives 5, ++a gives 7.

Why this answer

The code initializes an integer array with values 1 through 5. The for loop iterates over each element using the enhanced for loop, and the variable 'x' takes on each value in sequence. The loop adds each element to the variable 'sum', which starts at 0.

After processing all five elements (1+2+3+4+5), sum equals 15. Then, the code prints the value of 'sum' minus 3, which is 12. Option C is correct.

Exam trap

The trap here is that candidates may misread the code and think the loop only sums a subset of elements, or they may incorrectly compute the sum (e.g., forgetting to include the last element) or misapply the subtraction, leading to a wrong answer like 10, 11, or 13.

How to eliminate wrong answers

Option A is wrong because 10 would be the result if the loop only summed the first four elements (1+2+3+4) and then subtracted 0, or if a different arithmetic error occurred. Option B is wrong because 13 would be the result if the sum was 16 and then 3 was subtracted, or if the loop incorrectly skipped an element or added an extra value. Option D is wrong because 11 would be the result if the sum was 14 (e.g., missing one element like 5) and then 3 was subtracted, or if the subtraction was misapplied.

83
MCQeasy

Which primitive data type should be used to store a single character?

A.int
B.byte
C.char
D.String
AnswerC

char is a 16-bit Unicode character.

Why this answer

Option C is correct because the `char` primitive data type in Java is specifically designed to store a single 16-bit Unicode character, ranging from '\u0000' (0) to '\uffff' (65,535). It can represent any character in the Unicode standard, including letters, digits, and symbols, making it the appropriate choice for a single character value.

Exam trap

Oracle often tests the distinction between primitive and reference types, and the trap here is that candidates confuse `String` (a reference type) with `char` (a primitive type) because both are used for text, leading them to incorrectly select `String` for a single character.

How to eliminate wrong answers

Option A is wrong because `int` is a 32-bit signed integer type used for whole numbers, not for storing characters; while it can hold a character's numeric code point, it is not the primitive type intended for character storage and requires explicit casting to be used as a character. Option B is wrong because `byte` is an 8-bit signed integer type with a range of -128 to 127, which is insufficient to represent the full Unicode character set (0 to 65,535) and cannot store most characters without data loss or overflow. Option D is wrong because `String` is a reference type (a class) that represents a sequence of characters, not a primitive type; it is used for strings of text, not a single character, and using it for a single character introduces unnecessary overhead and violates the requirement for a primitive data type.

84
MCQmedium

You are writing a program that processes a list of transactions. Each transaction has a timestamp (long), amount (double), and type (String). The program needs to iterate through the transactions in the order they were added. Which collection should you use to maintain insertion order and allow fast iteration?

A.TreeSet<Transaction>
B.LinkedList<Transaction>
C.HashSet<Transaction>
D.ArrayList<Transaction>
AnswerD

Maintains insertion order, fast iteration.

Why this answer

ArrayList maintains insertion order and provides O(1) random access and fast iteration via index-based traversal. It is the correct choice when you need to preserve the order in which elements were added and iterate over them sequentially without requiring sorting or unique constraints.

Exam trap

Oracle often tests the misconception that LinkedList is the best choice for insertion-order preservation and iteration, but ArrayList is actually faster for iteration due to contiguous memory and lower overhead, while LinkedList is better for frequent insertions/removals at the beginning or middle.

How to eliminate wrong answers

Option A is wrong because TreeSet sorts elements by their natural order or a provided comparator, not by insertion order, and it does not allow duplicates. Option B is wrong because LinkedList maintains insertion order but has slower iteration performance due to node-based traversal and higher memory overhead compared to ArrayList. Option C is wrong because HashSet does not guarantee any order; it uses hash codes to store elements and may reorder them arbitrarily.

85
MCQhard

Refer to the exhibit. What is the output when running the main method?

A.B A C
B.A B C
C.A C B
D.C B A
AnswerB

Static init block, then instance init block, then constructor.

Why this answer

The correct answer is B because the code demonstrates a standard Java class hierarchy with method overriding and the use of the `super` keyword. When `new C()` is instantiated, the constructor of `C` calls `super()` (implicitly or explicitly), which invokes the constructor of `B`. In `B`, the constructor calls `super()` again, invoking the constructor of `A`.

Since `A`'s constructor prints 'A', then `B`'s constructor prints 'B', and finally `C`'s constructor prints 'C', the output is 'A B C'.

Exam trap

Oracle often tests the order of constructor execution in inheritance, and the trap here is that candidates mistakenly think constructors execute from child to parent (like destructors in C++) or confuse the output order with method overriding behavior, leading them to choose 'C B A' or 'B A C'.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 'B A C', which would occur if constructors were called in reverse order or if `super()` was not used correctly, but Java always calls parent constructors first. Option C is wrong because it suggests 'A C B', which would happen if `C`'s constructor printed before `B`'s, but `super()` in `C` invokes `B`'s constructor before `C`'s own print statement. Option D is wrong because it suggests 'C B A', which would be the order of a destructor chain or if constructors were called from child to parent, but Java constructors execute from the top of the hierarchy down.

86
Multi-Selecthard

Which THREE are valid Java identifiers? (Choose three.)

Select 3 answers
A.$dollar
B.my var
C.2ndValue
D._value
E.myVar123
AnswersA, D, E

Starts with dollar sign, valid.

Why this answer

Option A is correct because Java identifiers can start with a dollar sign ($), which is a valid identifier character according to the Java Language Specification (JLS). The $dollar follows the rule that identifiers must begin with a letter, underscore, or dollar sign, and subsequent characters can include letters, digits, underscores, or dollar signs.

Exam trap

Oracle often tests the rule that identifiers cannot start with a digit, leading candidates to mistakenly think '2ndValue' is valid because it contains letters, while overlooking the initial digit violation.

87
MCQhard

What is the result of: Integer a = null; int b = (a != null) ? a : 0; System.out.println(b);

A.0
B.NullPointerException
C.Compilation error
D.null
AnswerA

Correct. Ternary returns 0.

Why this answer

The ternary operator evaluates the condition (a != null). Since a is null, the condition is false, so the expression returns the second operand, which is the int literal 0. This value is assigned to int b, and System.out.println(b) prints 0.

No NullPointerException occurs because the ternary operator never attempts to unbox a null reference.

Exam trap

Oracle often tests the misconception that accessing a null reference in any part of a ternary expression will throw a NullPointerException, but the key is that the unboxing only occurs if the selected branch actually references the null object.

How to eliminate wrong answers

Option B is wrong because a NullPointerException would only occur if the ternary operator attempted to auto-unbox a null Integer to int, but the condition (a != null) is false, so the expression evaluates to the int literal 0, not to a. Option C is wrong because the code compiles successfully; the ternary operator is syntactically valid and both operands are compatible with int assignment. Option D is wrong because b is a primitive int, which cannot hold a null value; the output is the integer 0, not the string 'null'.

88
MCQhard

A developer writes: int x = 5; int y = x++ + ++x; What is the value of y after execution?

A.12
B.11
C.10
D.Compilation error
AnswerA

x++ uses 5 then increments to 6; ++x increments to 7 then uses 7; sum is 12.

Why this answer

The expression `int y = x++ + ++x;` involves post-increment and pre-increment operators. Initially, `x = 5`. In `x++`, the current value (5) is used, then `x` becomes 6.

In `++x`, `x` is incremented to 7, then the new value (7) is used. So, `y = 5 + 7 = 12`. Option A is correct.

Exam trap

Cisco often tests the confusion between post-increment and pre-increment operators, where candidates mistakenly assume both increments use the same value or overlook the order of evaluation.

How to eliminate wrong answers

Option B (11) is wrong because it incorrectly assumes both increments use the same intermediate value (e.g., 5 + 6). Option C (10) is wrong because it might assume both increments use the original value (5 + 5) or misapply operator precedence. Option D (compilation error) is wrong because the expression is syntactically valid in Java; post-increment and pre-increment can be used together in an expression without error.

89
MCQmedium

A developer writes: if (x = 5) { System.out.println("x is 5"); } What is the result?

A.Compilation error
B.Prints "x is 5" if x equals 5
C.No output
D.Prints "x is 5" always
AnswerA

Assignment is not boolean and cannot be used in if condition.

Why this answer

In Java, the assignment operator `=` is used for assignment, not comparison. The expression `x = 5` assigns the value 5 to variable `x` and returns the assigned value (5). Since the condition in an `if` statement must be a boolean expression, and `int` cannot be implicitly converted to `boolean`, the compiler throws a compilation error.

This is a fundamental syntax rule in Java, unlike in C/C++ where such an assignment would be allowed as a truthy check.

Exam trap

Oracle often tests the distinction between assignment (`=`) and comparison (`==`) in conditional statements, exploiting the common misconception that Java behaves like C/C++ where an assignment expression can be used as a boolean condition.

How to eliminate wrong answers

Option B is wrong because the code does not compile, so it never executes to check if x equals 5. Option C is wrong because a compilation error occurs before any runtime output, so there is no 'no output' scenario. Option D is wrong because even if the code compiled (which it does not), the assignment would always set x to 5, but the condition would still be a non-boolean type, causing a compilation error; thus it never prints anything.

90
Multi-Selectmedium

Which TWO keywords are used to control access to class members? (Choose two.)

Select 2 answers
A.private
B.static
C.public
D.abstract
E.final
AnswersA, C

Correct: private restricts access to within the class.

Why this answer

Option A is correct because the `private` keyword restricts access to the class member so that it can only be accessed within the same class. Option C is correct because the `public` keyword allows access to the class member from any other class in any package. These are two of the four access modifiers in Java (private, default, protected, public) that directly control visibility and access to class members.

Exam trap

Oracle often tests the distinction between access modifiers (private, public) and non-access modifiers (static, abstract, final), so the trap here is that candidates confuse keywords that affect behavior or structure with those that control visibility and access to class members.

91
MCQeasy

What is the result of: int[] arr = new int[5]; System.out.println(arr[5]);

A.ArrayIndexOutOfBoundsException
B.null
C.-1
D.0
AnswerA

Correct. Runtime exception thrown.

Why this answer

Option A is correct because Java arrays are zero-indexed, meaning a valid index for an array of length 5 is 0 through 4. Accessing index 5 throws an ArrayIndexOutOfBoundsException at runtime, as it is outside the array's bounds.

Exam trap

Oracle often tests the misconception that accessing an out-of-bounds index returns a default value like 0 or null, or that Java silently wraps around, when in fact it always throws an exception.

How to eliminate wrong answers

Option B is wrong because an array of primitive int cannot store null; only object arrays can have null elements, and accessing an out-of-bounds index throws an exception, not returns null. Option C is wrong because Java does not return -1 for out-of-bounds array access; that behavior is specific to methods like String.indexOf(), not array indexing. Option D is wrong because while uninitialized int array elements default to 0, accessing an invalid index does not return the default value—it throws an exception.

92
MCQeasy

Which data type should be used to store a single character like 'A'?

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

Correct: char stores a single 16-bit Unicode character.

Why this answer

In Java, the `char` data type is a single 16-bit Unicode character, capable of storing any character from the Unicode standard, including 'A'. It is the primitive type specifically designed for a single character, whereas `String` is a reference type for sequences of characters.

Exam trap

Oracle often tests the distinction between `char` and `String` by presenting a single character literal like 'A' and expecting candidates to recognize that `char` uses single quotes while `String` uses double quotes, leading some to incorrectly choose `String` due to familiarity with text handling.

How to eliminate wrong answers

Option A is wrong because `String` is a reference type used for sequences of characters, not a single character; using it for a single character introduces unnecessary object overhead. Option C is wrong because `byte` is an 8-bit integer type with a range of -128 to 127, which cannot directly represent most Unicode characters like 'A' without casting and loss of character semantics. Option D is wrong because `int` is a 32-bit integer type, which can technically hold a character's numeric value but is not intended for character storage and lacks the semantic clarity and type safety of `char`.

93
MCQhard

A developer is working on a Java application that processes user input. The application reads an integer from the command line using args[0], converts it to an int, and uses it in a loop. When testing, the application throws a NumberFormatException when the user provides an alphabetic string. The developer needs to handle this exception gracefully by prompting the user to enter a valid number and retrying. However, the developer must avoid infinite loops. The current code uses a while loop with a flag. Which approach ensures the code handles the exception, provides feedback, and terminates if the user enters 'quit'? The environment is a standard Java SE 11 application. The developer wants a robust solution without using external libraries.

A.Use a try-catch inside a loop that continues if exception caught, and breaks if input equals 'quit' or conversion succeeds.
B.Catch the exception and ignore it; the loop will naturally terminate.
C.Use a do-while loop that never checks for 'quit'; the exception is caught outside the loop.
D.Catch the exception in the loop and call System.exit(0) immediately.
AnswerA

Correct: handles exception, allows retry, and exits on 'quit'.

Why this answer

Option B is correct because it catches NumberFormatException, prints a message, and allows retry, but sets the flag to false if user enters 'quit' to exit.

94
MCQhard

Given the code: int[] arr = {1,2,3}; for(int x : arr) { if(x==2) continue; System.out.print(x); } What is the output?

A.2
B.Compilation error
C.13
D.123
AnswerC

1 and 3 are printed.

Why this answer

The enhanced for loop iterates over the array {1,2,3}. When x equals 2, the continue statement skips the remainder of the loop body for that iteration, so System.out.print(x) is not executed for 2. Thus, only 1 and 3 are printed, producing output '13'.

Exam trap

The trap here is that candidates often confuse continue with break, thinking continue terminates the loop entirely, or they forget that continue skips only the current iteration's remaining code, leading them to include the skipped value in the output.

How to eliminate wrong answers

Option A is wrong because it suggests the output is '2', but the continue statement skips printing 2, so 2 is not output. Option B is wrong because the code compiles successfully; the enhanced for loop and continue are valid Java syntax. Option D is wrong because it includes '2' in the output, but the continue statement prevents 2 from being printed, so the output is '13', not '123'.

95
Multi-Selecthard

Which THREE are primitive data types in Java? (Choose three.)

Select 3 answers
A.int
B.boolean
C.String
D.double
E.Object
AnswersA, B, D

int is a primitive integer type.

Why this answer

Option A is correct because `int` is a primitive data type in Java that stores 32-bit signed integer values. Primitive types are predefined by the language and are not objects, meaning they are stored directly on the stack for efficiency.

Exam trap

Oracle often tests the distinction between primitive types and commonly used reference types like `String` and `Object`, exploiting the misconception that `String` behaves like a primitive because of its special language support (e.g., string literals and the `+` operator).

96
MCQeasy

A developer writes the following code: int x = 5; System.out.println(x++); What is the output?

A.Compilation error
B.5
C.6
D.Runtime exception
AnswerB

x++ returns 5, then x becomes 6.

Why this answer

The expression `x++` is a post-increment operator, which returns the current value of `x` (5) before incrementing it. Therefore, `System.out.println(x++)` prints 5, and then `x` becomes 6. Option B is correct because the output is the original value of `x`.

Exam trap

Oracle often tests the difference between post-increment and pre-increment operators, where candidates mistakenly think `x++` prints the incremented value (6) instead of the original value (5).

How to eliminate wrong answers

Option A is wrong because the code compiles successfully; post-increment is a valid Java operator. Option C is wrong because it reflects a misunderstanding of post-increment vs. pre-increment; `x++` prints the value before increment, not after. Option D is wrong because no runtime exception occurs; the operation is well-defined and safe.

97
MCQmedium

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

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

Correct: concatenation yields 'Hello World'.

Why this answer

Option D is correct because the + operator performs string concatenation in Java. s1 + s2 combines "Hello" and " World" to produce "Hello World", which is then printed. The space is part of s2, so the output includes it.

Exam trap

Oracle often tests whether candidates notice the leading space in s2 (" World") versus assuming no space, leading them to choose Option A ("HelloWorld") instead of the correct output with the space.

How to eliminate wrong answers

Option A is wrong because it omits the space between "Hello" and "World", but s2 starts with a space, so the concatenation includes it. Option B is wrong because it shows "Hello World" without the leading space, but the actual output is "Hello World" with the space from s2. Option C is wrong because the code compiles and runs without error; string concatenation with + is valid Java syntax.

98
MCQhard

Given int[] arr = {1,2,3}; which correctly creates a new array with length 5 and copies the contents of arr?

A.int[] newArr = new int[5]; newArr = arr;
B.int[] newArr = arr.clone(); newArr.length = 5;
C.int[] newArr = Arrays.copy(arr, 5);
D.int[] newArr = Arrays.copyOf(arr, 5);
AnswerD

Arrays.copyOf creates a new array with specified length and copies elements.

Why this answer

Option D is correct because `Arrays.copyOf(int[] original, int newLength)` creates a new array of the specified length (5) and copies the elements from the original array into it, padding with default values (0 for int) for any extra positions. This method is specifically designed for this task, ensuring the original array remains unchanged.

Exam trap

The trap here is that candidates often confuse reference assignment (`=`) with array copying, or they misremember the exact method name (`Arrays.copy` vs `Arrays.copyOf`), leading them to pick options that either fail to copy or do not compile.

How to eliminate wrong answers

Option A is wrong because `newArr = arr;` merely assigns the reference of `arr` to `newArr`, discarding the previously allocated `new int[5]` array; both variables then point to the same 3-element array, so no copy occurs and the length is not 5. Option B is wrong because `arr.clone()` creates a new array of the same length (3), and `newArr.length = 5;` is a compile-time error — array length is final and cannot be reassigned. Option C is wrong because `Arrays.copy(arr, 5)` is not a valid method; the correct method name is `Arrays.copyOf`, and `Arrays.copy` does not exist in the standard Java library.

99
MCQmedium

What is the scope of a variable declared inside a for loop?

A.Inside the package
B.Only inside the loop block
C.Inside the class
D.Inside the entire method
AnswerB

Correct: variables declared in for loop are local to that block.

Why this answer

In Java, a variable declared inside a for loop (including the initialization block or the loop body) has block scope, meaning it is only accessible within the loop block itself. This is defined by the Java Language Specification (JLS §6.10), which states that the scope of a local variable declaration is the rest of the block in which the declaration appears. Once the loop completes, the variable goes out of scope and cannot be referenced.

Exam trap

Oracle often tests the misconception that a variable declared in the for loop's initialization block has method-level scope, leading candidates to incorrectly choose 'Inside the entire method' when the variable is actually scoped only to the loop block.

How to eliminate wrong answers

Option A is wrong because a variable declared inside a for loop is not accessible at the package level; package scope applies to members declared with default (package-private) access within a class, not to local variables. Option C is wrong because class scope applies to instance or static fields declared directly in the class body, not to variables declared inside a loop. Option D is wrong because method scope would allow the variable to be used anywhere within the method, but a variable declared inside a for loop is confined to the loop block and cannot be accessed after the loop ends.

100
MCQeasy

What is the value of the expression (10 > 5) && (3 < 2)?

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

The second condition is false.

Why this answer

The expression (10 > 5) evaluates to true, and (3 < 2) evaluates to false. The logical AND operator (&&) returns true only if both operands are true. Since one operand is false, the entire expression evaluates to false.

In Java, the result of a boolean expression is a boolean literal, not an integer.

Exam trap

Oracle often tests the distinction between boolean and integer types in Java, trapping candidates who expect true/false to be represented as 1/0 as in C or JavaScript.

How to eliminate wrong answers

Option A is wrong because 1 is an integer literal, but the && operator in Java returns a boolean (true or false), not an int. Option B is wrong because the expression does not evaluate to true; the second operand (3 < 2) is false, making the entire AND expression false. Option D is wrong because 0 is an integer literal, and Java does not implicitly convert integers to booleans in logical expressions; the result is a boolean false, not the integer 0.

101
MCQeasy

A developer writes: int x; System.out.println(x); What is the result?

A.null
B.Compilation fails
C.Runtime error
D.0
AnswerB

Correct. The variable x is not initialized.

Why this answer

Local variables must be initialized before use. x is not initialized, so compilation fails.

102
MCQhard

A developer uses a switch statement with a String variable. Which is true about this usage?

A.It works only with primitive types
B.It causes a compilation error because strings are not supported
C.It works with strings starting from Java 7
D.It requires a default case
AnswerC

Switch on strings is valid since Java 7.

Why this answer

Option C is correct because, starting from Java 7 (JSR 334), the switch statement supports String objects in addition to primitive types and enums. The compiler uses the `hashCode()` and `equals()` methods of the String class to evaluate the switch expression against case labels, making it a valid and efficient way to branch on string values.

Exam trap

Oracle often tests the Java version where String support was introduced (Java 7), and the trap here is that candidates who learned Java before 7 or who confuse switch with older limitations may incorrectly think Strings are not allowed or that only primitives work.

How to eliminate wrong answers

Option A is wrong because switch statements in Java support not only primitive types (int, char, byte, short) but also enumerated types and, since Java 7, String objects. Option B is wrong because String support was explicitly added in Java 7; it does not cause a compilation error in Java 7 or later. Option D is wrong because a default case is optional in a switch statement; it is only required if you need to handle values that do not match any case label, but the compiler does not enforce its presence.

← PreviousPage 2 of 2 · 103 questions total

Ready to test yourself?

Try a timed practice session using only Java Basics Syntax questions.