Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
15 / 15 published solutions
Question 2 MCQ · 3.0 marks
Consider the Java code below.
Choose the correct option.
6406537086518.
The output is:
6406537086519.
generates compilation error because a variable of type
cannot refer to an object of type
.
6406537086520.
The output is:
6406537086521.
The output is:
Published solution
**1. Check reference compatibility:** ProjectManager extends Manager, so a Manager variable can legally refer to a ProjectManager object. This is an upcast.
**2. Resolve work():** obj.work() calls the overridden no-argument method in the runtime class ProjectManager. That method calls super.work(), which enters Manager.work(). Manager.work() first calls Employee.work(). The print sequence is therefore 'Employee is working', 'Manager is managing the team', and 'Project Manager is coordinating the project'.
**3. Resolve work(String):** The compiler selects the String overload, which exists in Manager. ProjectManager does not override that signature, so the inherited method prints 'Manager is working on project: Payroll System'. Overloading selects a signature; overriding selects the runtime implementation of that signature.
**Answer: A.**
A: **Correct:** This includes all three prints in the super-call chain and the inherited String-overload output.
B: **Incorrect:** A superclass reference can point to a subclass object.
C: **Incorrect:** The no-argument call must also execute ProjectManager.work().
D: **Incorrect:** The call to Manager.work() prints the manager message before returning to ProjectManager.
**1. Separate static and instance fields:** accountNumber is static, so there is one shared counter for the BankAccount class. balance belongs to each individual object. interestRate is an instance constant initialized to 4.5 in each account.
**2. Construct both objects:** Creating acc1 increments the initially zero counter to 1 and stores its balance as 1000. Creating acc2 increments the same counter to 2 and stores its balance as 2000.
**3. Print after construction:** Both toString calls read the current shared accountNumber, which is already 2. Consequently the lines are '2, 4.5, 1000.0' and '2, 4.5, 2000.0'. A shared counter is not an individual account identifier unless a separate instance field captures its value.
**Answer: B.**
A: **Incorrect:** This incorrectly treats the shared counter as a separate stored number for each account.
B: **Correct:** Both objects read the final shared counter 2 but retain different balances.
C: **Incorrect:** The counter has been incremented twice before either object is printed.
D: **Incorrect:** Balances are instance fields; the first account does not acquire the second account's balance.
**1. Inspect the array:** The Object[] contains a RotationMatrix, a ScalingMatrix and a String. Only the first two implement Transformable.
**2. Check before casting:** Use if(arr[i] instanceof Transformable) ((Transformable)arr[i]).transform();. The test skips the String and establishes that the cast is safe.
**3. Use dynamic dispatch:** Calling transform through the interface invokes the matching implementation for each object. The lines are 'Applying Rotation Matrix' and 'Applying Scaling Matrix'. Casting every element to one concrete class would fail on other types.
**Answer: B.**
A: **Incorrect:** Object does not declare transform(), so arr[i].transform() cannot compile with the declared array type.
B: **Correct:** The interface test and cast accept both implementations and skip the String.
C: **Incorrect:** The ScalingMatrix and String entries cannot be cast to RotationMatrix.
D: **Incorrect:** The RotationMatrix and String entries cannot be cast to ScalingMatrix.
Consider the Java code given below that checks whether a necklace has a mirror pattern of beads
(i.e., the sequence of bead colors is the same when viewed from both ends).
Choose the correct option to fill in place of
so that the output is:
You may make use of the descriptions of the methods given below. These are methods inside type
.
: Retrieves and removes the last element of this deque, or returns
if this deque
is empty.
: Retrieves and removes the head of this deque, or returns
**1. Define the mirror test:** A palindrome has equal characters at matching positions from the two ends. A deque supports removing from both ends using poll() and pollLast().
**2. Compare each pair:** The appropriate block repeatedly removes the first and last Character and returns false immediately if !q.poll().equals(q.pollLast()). If every pair matches, execution reaches the final return true.
**3. Trace the examples:** For RBGGBR, the pairs are R/R, B/B and G/G, so the result is true. For RBGYBR, R/R and B/B match but G/Y differs, so the result is false.
**Scope note:** Both supplied strings have even length. A general solution should use while(q.size()>1), so an odd-length palindrome's middle character is not compared with null.
**Answer: B.**
A: **Incorrect:** Breaking out on a mismatch still reaches the unconditional return true, incorrectly accepting a non-palindrome.
B: **Correct:** Value equality is checked and any mismatched pair causes an immediate false return.
C: **Incorrect:** It returns false when a matching pair is encountered, reversing the intended test; == also compares wrapper references.
D: **Incorrect:** It removes characters without checking them and then returns false regardless of their values.
**1. Apply eligibility:** A completed survey is eligible regardless of its response count. An incomplete survey is eligible only when responses are at least 10.
**2. Check the data:** Student Feedback has 15 responses and is kept. Library Usage has 8 responses and is incomplete, so it must be removed. Campus Facilities and Hostel Satisfaction are both complete and are kept.
**3. Remove safely while iterating:** iterator.remove() removes the element most recently returned by iterator.next() and keeps the iterator's structural-modification state consistent. The result is [Student Feedback, Campus Facilities, Hostel Satisfaction].
**Answer: B.**
A: **Incorrect:** Iterator.remove takes no element argument.
B: **Correct:** This removes the current Library Usage entry through the active iterator.
C: **Incorrect:** List.remove() has no applicable no-argument overload here.
D: **Incorrect:** Changing the underlying list directly can invalidate its active iterator and cause concurrent-modification failure.
**1. Notice the destination:** finalScores is a new empty TreeMap. The loop visits penaltyPoints, not originalScores. Therefore Alice, Bob and David are the keys encountered.
**2. Understand merge on an absent key:** Map.merge(key,value,remappingFunction) inserts value directly when the key has no existing non-null value. The remapping function is not called in that case.
**3. Trace C:** For Alice, merge inserts 10; for Bob, 5; for David, 3. No key is repeated, so subtraction never occurs. TreeMap then prints the keys in natural order: {Alice=10, Bob=5, David=3}. The variable name finalScores does not change what the code actually does.
**Answer: C.**
A: **Incorrect:** This inserts original scores, including null for David rather than David's penalty 3.
B: **Incorrect:** This attempts original-score subtraction; David has no original score and unboxing null would fail.
C: **Correct:** All keys are initially absent, so merge inserts each supplied penalty value directly.
D: **Incorrect:** This supplies originalScores values to merge; David's missing value is null and is invalid for this merge operation.
Consider two Java files located in two different packages as shown below.
Choose the correct option.
6406537086554.
and
generate compilation errors.
6406537086555.
generates a compilation error, while others compile fine.
6406537086556.
,
, and
generate compilation errors.
6406537086557.
Only
generates a compilation error.
Published solution
**1. Check LINE 1:** courseCode has no access modifier, so it has package-private access. ElectiveCourse is in com.student, whereas Course is in com.university. Access is therefore disallowed even through a subclass object.
**2. Check LINE 2:** courseName is private to Course. A subclass cannot read that field directly.
**3. Check the methods:** enrollStudent is protected. Code inside the subclass can invoke the inherited protected method through an ElectiveCourse reference. displayCourse is public and may be invoked normally. Thus only LINE 1 and LINE 2 fail compilation.
**Answer: A.**
A: **Correct:** The default-access field and private field are both inaccessible from this different-package subclass.
B: **Incorrect:** LINE 1 also fails because package-private access does not cross package boundaries.
C: **Incorrect:** LINE 3 is allowed as protected access through the subclass reference from within the subclass.
D: **Incorrect:** LINE 3 is permitted; the inaccessible fields are the actual problem.
**1. Enable assertions:** The command uses -enableassertions, so assert statements are evaluated. A false condition throws AssertionError.
**2. Follow execution order:** The first statement constructs Satellite(-500). Its condition is o>0. Substitution gives -500>0, which is false, so assert-2 throws immediately.
**3. Stop at the first failure:** Execution does not reach SpaceProbe(10) or Rocket(120). Rocket's condition would fail if executed, but it is not the first assertion encountered. Always trace runtime order, not the order of class definitions.
**Answer: B.**
A: **Incorrect:** Rocket(120) is never reached after the earlier Satellite construction fails.
B: **Correct:** Satellite(-500) is created first and its positive-height assertion fails.
C: **Incorrect:** The SpaceProbe constructor is not reached; its value 10 would satisfy b>=0 anyway.
D: **Incorrect:** Assertions are enabled and the first constructor contains a failing condition.
**1. Identify aliases and copies:** p1 is the original Pen with price 100. p2 is a new object built by the copy constructor. p3=p1 is only a second reference to the original object. p4=p1.clone() is another new Product object because Product implements Cloneable and its clone method calls super.clone().
**2. Change the original:** p1 is changed to Pencil with price 30. p3 sees the same object, so it also prints Pencil : 30.0. p2 and p4 keep their independent field values Pen : 100.0.
**3. Read the print order:** The four values are Pencil : 30.0, Pen : 100.0, Pencil : 30.0, Pen : 100.0. Shallow copying is sufficient for these fields because the name is an immutable String and the price is a primitive double.
**Answer: C.**
A: **Incorrect:** The copy constructor and clone create separate objects; they do not all alias p1.
B: **Incorrect:** The clone p4 retains the original Pen fields rather than changing with p1.
C: **Correct:** Only p3 aliases p1; p2 and p4 retain the original values.
D: **Incorrect:** Product implements Cloneable, and its clone method delegates to super.clone successfully.
This program generates a compilation error because
of type
cannot invoke method
.
6406537086577.
and
generate compilation errors because static interface
methods cannot be accessed using the interface name.
Published solution
**1. Distinguish declared and runtime types:** app is declared as AppointmentService, even though its object is HealthBuddyApp. Compile-time method lookup uses the declared reference type.
**2. Check each call:** bookAppointment is declared by AppointmentService, so app.bookAppointment() is allowed and would dispatch to HealthBuddyApp's override. trackHealth belongs to HealthTracker, not AppointmentService, so app.trackHealth() cannot compile through this reference.
**3. Check static interface methods:** AppointmentService.status() and HealthTracker.status() are correctly invoked using their declaring interface names. The overall program fails compilation before any output is produced.
**Answer: C.**
A: **Incorrect:** The listed runtime output ignores the compile-time failure of app.trackHealth().
B: **Incorrect:** This also assumes successful compilation; static methods would additionally print their own interface-specific messages.
C: **Correct:** AppointmentService does not expose trackHealth, so this method call is not permitted through app.
D: **Incorrect:** The interface-qualified static calls are the correct way to invoke these methods.
**1. Erase an unbounded type parameter:** In <T> void traverse(T[] vertices), T has implicit upper bound Object. Erasure therefore changes the parameter type to Object[].
**2. Erase a bounded parameter:** In <T extends Number> double totalWeight(T[] edgeWeights), T erases to its first bound, Number. The array type becomes Number[]. The primitive double return type remains unchanged.
**3. Remove generic declarations:** The erased methods are void traverse(Object[] vertices) and double totalWeight(Number[] edgeWeights). The bound is not arbitrarily changed to Double, and a bare T cannot remain after erasure.
**Answer: A.**
A: **Correct:** Object[] and Number[] are the correct erased parameter types.
B: **Incorrect:** The Number upper bound must be retained as Number rather than erased further to Object.
C: **Incorrect:** The type variable T cannot remain as an undeclared erased type.
D: **Incorrect:** Number is the declared bound; erasure does not specialize it to Double.
will print entries in the order in which they were inserted.
will print entries in sorted order of keys.
6406537086543.
will print entries in unspecified order.
will print entries in sorted order of keys.
6406537086544.
will print entries in sorted order of keys.
will print entries in insertion order.
6406537086545.
Both
and
will print entries in unspecified
order.
Published solution
**1. HashMap ordering:** missionMap is a HashMap. Its iteration order is unspecified; an observed order on one run is not an insertion-order or sorted-order guarantee.
**2. TreeMap ordering:** sortedMissionMap is constructed from the same entries but is a TreeMap<Integer,String>. With no custom comparator, it iterates in ascending natural order of integer keys: 1, 2, 3, 4.
**3. Match keys to missions:** Its ordered lines associate 1 with Launch Rocket, 2 with Orbit Earth, 3 with Deploy Satellite and 4 with Collect Space Samples. Copying entries into a TreeMap changes their ordering policy, not their key/value associations.
**Answer: B.**
A: **Incorrect:** HashMap does not guarantee insertion-order iteration.
B: **Correct:** HashMap has unspecified order, while TreeMap uses sorted keys.
C: **Incorrect:** The ordering guarantees are assigned to the wrong map types.
D: **Incorrect:** TreeMap does guarantee its comparator-based or natural key order.
**1. Compare capacities:** books contains three IDs: 101, 102 and 103. shelf is an int array of length 2, whose only valid indices are 0 and 1.
**2. Trace the loop:** At i=0, shelf[0]=101 succeeds and prints 101. At i=1, shelf[1]=102 succeeds and prints 102. At i=2, shelf[2]=103 attempts an invalid array index and throws ArrayIndexOutOfBoundsException before its print statement.
**3. Follow exception handling:** The catch inside assignShelf catches this exception and prints 'cannot assign'. It does not rethrow it, so the outer catch in main does not run. Final lines: 101, 102, cannot assign.
**Answer: B.**
A: **Incorrect:** The inner catch handles the exception, so the outer catch does not also print.
B: **Correct:** The two successful assignments print before the inner catch message.
C: **Incorrect:** There is no index 2 in an array of length 2, so 103 is not assigned or printed.
D: **Incorrect:** The earlier successful assignments do print, and no exception escapes to main.
**1. Match the actual argument:** movies is declared Movie[] and contains both ActionMovie and ComedyMovie objects. The method must accept this mixed interface-typed array.
**2. Use the interface directly:** A parameter Movie[] movies accepts the array and permits getRating() on every element, because that method is declared in Movie. The ratings are 8, 7 and 9, so the highest is 9.
**3. Use a compatible generic bound:** <T extends Movie> with parameter T[] also works: T can be inferred as Movie. It makes the getRating method available through the upper bound.
**4. Reject narrower or invalid types:** A parameter written simply as (<?> movies) is not a valid standalone wildcard-array declaration. A T extends ActionMovie bound cannot accept the mixed Movie[] containing ComedyMovie.
**Answer: B, D.**
A: **Incorrect:** The wildcard syntax shown is not a valid parameter type for this array.
B: **Correct:** The Movie bound guarantees getRating, and T may be inferred as Movie for the supplied array.
C: **Incorrect:** An ActionMovie-only bound excludes the declared Movie[] and its ComedyMovie element.
D: **Correct:** The direct Movie[] parameter exactly matches the argument and exposes getRating.
**1. State the condition:** A tree is eligible when both height>=2 and height<=5 hold. The endpoints are included.
**2. Test each tree:** Neem at 2.8 and Ashoka at 3.4 satisfy both inequalities. Banyan at 6.5 and Peepal at 7.2 exceed 5; Mango at 1.5 is below 2. Therefore print Neem and Ashoka in their list encounter order.
**3. Compare stream operations:** filter keeps Tree objects that satisfy a predicate. One combined filter and two consecutive filters implement the same logical AND. map transforms each Tree into the returned value; mapping to a Boolean discards access to the tree's name.
**Answer: B, C.**
A: **Incorrect:** The first map produces Booleans, so the final lambda cannot access a Tree name on each Boolean.
B: **Correct:** One filter with both inclusive bounds keeps exactly Neem and Ashoka.
C: **Correct:** Two filters keep objects satisfying both predicates, giving the same eligible trees.
D: **Incorrect:** The map changes the remaining elements into Booleans, so s.name is invalid.