**1. Trace insertion and accumulation:** The first TEMP01 reading creates a total of 1500. HUMID02 creates 2000 and AIRQ03 creates 1200. The final TEMP01 reading uses its existing value and adds 800, giving 2300.
**2. Identify the ordering rule:** LinkedHashMap preserves insertion order in the constructor mode shown. Updating the value of an existing key does not move it to a new insertion position.
**3. Print the entries:** The totals therefore appear in first-seen order: TEMP01=2300, HUMID02=2000, AIRQ03=1200, with the spaces and separators produced by println.
**Answer: B — Lines: TEMP01 = 2300; HUMID02 = 2000; AIRQ03 = 1200.**
A: **Incorrect:** It replaces the repeated TEMP01 total with the last reading 800 instead of adding it to 1500.
B: **Correct:** It correctly accumulates TEMP01 to 2300 and retains first-insertion ordering.
C: **Incorrect:** This reorders the entries rather than preserving the shown LinkedHashMap insertion sequence.
D: **Incorrect:** This also changes the insertion order even though updating a value does not reorder keys.
Consider the Java code given below that prints the credit points of courses. From among the
options, identify the appropriate function header for the function
that takes as
input a list of courses and prints their credit points.
**1. Identify the two argument types:** The caller passes List<MathCourse> and List<LinguisticsCourse>. Both element classes extend Course, so their elements support getCredits().
**2. Apply generic invariance:** List<MathCourse> is not a subtype of List<Course>, and neither typed list is a List<Object>. A parameter declared with either of those types would reject the calls.
**3. Use an upper-bounded wildcard:** List<? extends Course> accepts lists of Course or its subclasses while allowing values read from the list to be treated as Course. The method can therefore iterate and call getCredits(), printing 3.0,4.0,2.5,3.5.
**Answer: C — public static void printCredits(List<? extends Course> lst).**
A: **Incorrect:** Java’s generic invariance prevents passing List<MathCourse> or List<LinguisticsCourse> as List<Course>.
B: **Incorrect:** This accepts the linguistics list but not the maths list.
C: **Correct:** The upper bound accepts both subtype lists and provides Course methods for reading their elements.
D: **Incorrect:** List<Object> does not accept arbitrary lists of subtypes, and Object itself has no getCredits method.
**1. Check the package boundary:** Word belongs to linguistics while LinguistTest belongs to analysis. LinguistTest is not declared as a subclass of Word.
**2. Check each access:** showSyllables is public, so LINE 1 may call it; that method can legally call Word’s own private getSyllables internally. getLanguage is protected and is not accessible through w from this unrelated external-package class, so LINE 2 fails.
**3. Check the last line:** getText is public and LINE 3 is valid. The single access violation is therefore LINE 2.
**Answer: B — Only LINE 2 generates a compilation error.**
**Convention note:** The placeholder constructor comment does not declare a constructor. The displayed public Word class therefore has its implicit public no-argument constructor, consistent with new Word().
A: **Incorrect:** LINE 1 is a public call; the private helper is called inside Word, where it is accessible.
B: **Correct:** Only LINE 2 directly accesses the protected method from an unrelated class in another package.
C: **Incorrect:** LINE 3 calls a public method and does not create a second error.
D: **Incorrect:** The protected access at LINE 2 is not legal in this context.
Consider the Java code given below about controlling robot hardware values.
Choose the correct option.
6406536627066.
and
generate a compilation error because method
is already defined with the same signature.
6406536627067.
and
generate a compilation error because method
is already defined with the same signature.
6406536627068.
Only
generates a compilation error because method
is
already defined with the same signature.
6406536627069.
This program generates output:
Published solution
**1. Compare the bounded methods:** LINE 1 declares <T extends Number> process(T), and LINE 2 declares <U extends Number> process(U). Renaming a type parameter does not create a different method signature. Both erase to process(Number).
**2. Compare the unbounded method:** LINE 3 declares <T> process(T), whose erased parameter type is Object. process(Object) is distinct from process(Number) and can coexist with one bounded declaration.
**3. Identify the error:** The second bounded declaration duplicates the first. The class does not compile as written, so the proposed runtime output is not produced.
**Answer: C — Only LINE 2 is the duplicate method declaration.**
A: **Incorrect:** LINE 3 erases to Object and is distinct; the duplicate is LINE 2 versus LINE 1.
B: **Incorrect:** LINE 1 and LINE 3 have different erased parameter types and are not the duplicate pair.
C: **Correct:** LINE 2 duplicates the already declared Number-bounded method despite using U instead of T.
D: **Incorrect:** Compilation fails before any call in main can produce output.
**1. Use the static element type:** SArr is declared Object[], so SArr[i] has compile-time type Object. Object has no process() method, even though the actual values implement Service.
**2. Cast to their shared interface:** Both CheckIn and Boarding implement Service. Casting each element to Service makes process available and remains valid for both runtime objects.
**3. Follow dispatch:** At index zero, CheckIn.process prints “Check-In Service”. At index one, Boarding.process prints “Boarding Service”. A cast to only one concrete class would fail on the other object.
**Answer: D — ((Service) SArr[i]).process();.**
A: **Incorrect:** process() cannot be called directly on the compile-time Object reference.
B: **Incorrect:** The first element is a CheckIn, so casting it to Boarding throws ClassCastException.
C: **Incorrect:** The second element is a Boarding, so casting every element to CheckIn fails there.
D: **Correct:** Both objects implement Service and their overridden methods are selected at runtime.
This code generates the output followed by runtime Error at
due to
ambiguity in
.
6406536627096.
This code generates the output:
6406536627097.
This code generates the output:
Published solution
**1. Resolve inherited apply:** The reference has type MatrixOp and points to SparseMatrixOp. MatrixOp inherits public apply() from Operation, so ob.apply() is accessible and prints “General linear operation”.
**2. Resolve compute:** MatrixOp defines compute(), and SparseMatrixOp does not override it. The next call prints “Matrix computation”.
**3. Resolve overridden describe:** SparseMatrixOp overrides describe(), so dynamic dispatch selects “Sparse Matrix description”. The superclass reference does not force the superclass implementation.
**Answer: C — Lines: General linear operation; Matrix computation; Sparse Matrix description.**
A: **Incorrect:** MatrixOp inherits the public apply method, so LINE 1 compiles.
B: **Incorrect:** A legal override is resolved by dynamic dispatch and does not create runtime ambiguity.
C: **Correct:** The output follows inherited apply, inherited compute and the runtime object’s overridden describe.
D: **Incorrect:** The final call selects SparseMatrixOp.describe rather than MatrixOp.describe.
**1. Identify superclass initialization:** CelestialBody has a constructor taking a String and no zero-argument constructor. Planet must explicitly initialize that superclass portion with the provided name.
**2. Choose constructor syntax:** super(n) invokes CelestialBody(String) and must appear before the body statements that initialize Planet’s own type field. It is not an ordinary method call.
**3. Follow printing:** super.toString() produces the name text, and Planet.toString adds the type. Printing the CelestialBody reference dispatches to Planet’s override, yielding “Name: Kepler-452b, Type: Super-Earth”.
**Answer: B — super(n);.**
A: **Incorrect:** this(n) would require a one-argument Planet constructor, which is not defined.
B: **Correct:** super(n) invokes the existing parent constructor and initializes its private name field.
C: **Incorrect:** A constructor is not invoked as an ordinary CelestialBody(n) method.
D: **Incorrect:** super.CelestialBody(n) is not Java’s superclass-constructor invocation syntax.
function is defined as:
If the specified key is not already associated with a value or is associated with
, associates it
with the given non-null value. Otherwise, replaces the associated value with the results of the
given remapping function, or removes if the result is
.
Consider the Java code given below.
Choose the correct option.
6406536627054.
generates a compilation error due to duplicate keys.
6406536627055.
The program generates the output:
6406536627056.
The program generates the output:
6406536627057.
The program generates the output:
Published solution
**1. Copy the first map:** The initial merged map contains Andromeda=88, Betelgeuse=76 and Cygnus=92. put assigns values by key and does not create a duplicate-key compilation error.
**2. Apply merge to shared keys:** Betelgeuse uses min(76,80)=76. Cygnus uses min(92,85)=85. Draco was absent, so merge inserts its supplied value 70 directly.
**3. Read TreeMap order:** Natural string-key order yields {Andromeda=88, Betelgeuse=76, Cygnus=85, Draco=70}. The operation chooses minima, not sums or maxima.
**Answer: B — {Andromeda=88, Betelgeuse=76, Cygnus=85, Draco=70}.**
A: **Incorrect:** Map key repetition is handled at runtime by replacement/merge rules; it is not a compilation error.
B: **Correct:** It retains or inserts each correct minimum and prints TreeMap’s sorted key order.
C: **Incorrect:** It uses larger values for the shared keys rather than the Math.min remapping.
D: **Incorrect:** It sums shared values, while the actual remapping function selects the smaller value.
Choose the correct option when the class is executed as:
6406536627062.
This code generates output:
6406536627063.
This code generates AssertionError:
6406536627064.
This code generates AssertionError:
6406536627065.
This code generates AssertionError:
Published solution
**1. Enable assertion evaluation:** The execution command includes -ea, so assertions are checked rather than skipped. The constructor receives aperture 150, which passes the positive-aperture assertion.
**2. Check the adjustment preconditions:** adjustZoom(300) passes amount>0. But currentZoom+amount is 800+300=1100, greater than maxZoom=1000.
**3. Follow failure control flow:** The second method assertion throws AssertionError with message “Zoom exceeds telescope limit” before the assignment and return. Therefore println never receives 1100.0 to print.
**Answer: C — AssertionError: Zoom exceeds telescope limit.**
A: **Incorrect:** 1100.0 would be reached if these assertions were disabled, but -ea enables the failing limit check.
B: **Incorrect:** The increment 300 is positive, so that assertion passes.
C: **Correct:** The proposed zoom 1100 exceeds the 1000 limit, causing this AssertionError.
D: **Incorrect:** The aperture is 150, so its positivity assertion passes.
**1. Apply the length filter:** premchand has nine characters and narayan has seven, so both pass length>6. tagore has six, desai five and bond four, so they are removed.
**2. Transform and skip:** map changes the two retained strings to PREMCHAND and NARAYAN. skip(1) removes the first retained stream element, PREMCHAND.
**3. Execute the terminal operation:** forEach prints the sole remaining element NARAYAN. No operation reorders this sequential list stream.
**Answer: B — NARAYAN.**
A: **Incorrect:** PREMCHAND is removed by skip(1), so both names are not printed.
B: **Correct:** After filtering and uppercasing, skipping the first element leaves NARAYAN alone.
C: **Incorrect:** The surviving second element is NARAYAN, not PREMCHAND.
D: **Incorrect:** TAGORE and DESAI fail the length>6 filter before the skip stage.
**1. Compare opposite traversal directions:** Pushing characters to a Stack makes pop read them backward. Adding them to a Deque makes poll read and remove them forward. A palindrome must have equal characters at every paired comparison.
**2. Use the rejection condition:** The code must return false when !s.pop().equals(d.poll()) is true. poll advances the front pointer on each comparison, unlike peek.
**3. Dry-run the examples:** LRRL yields comparisons L/L,R/R,R/R,L/L, all equal, so true is returned. LRLL compares L/L first, then L/R, so it returns false at the mismatch.
**Answer: C — while (!s.isEmpty()) { if (!s.pop().equals(d.poll())) return false; }.**
A: **Incorrect:** It rejects equality and repeatedly peeks at the same front character, violating the intended test.
B: **Incorrect:** It returns false on equal characters rather than on a mismatch.
C: **Correct:** It removes both compared characters and rejects only unequal pairs, implementing the palindrome test.
D: **Incorrect:** peek never advances the deque, so it repeatedly compares against the original first character.
**1. Map aliases and the clone:** a3 is the same Aircraft object as a1. a2 is a different Aircraft object made by the default shallow clone, but its flightHours field refers to the same underlying int array as a1’s.
**2. Modify the shared array:** a2.flightHours[1]=90 changes the shared array element, so a1,a2 and a3 all observe 90 at index one.
**3. Reassign the name field:** a3.airline="IndiGo" changes a1’s field because a3 aliases a1. a2 retains its own airline reference “Air India”; assigning a new String field does not mutate the old string.
**4. Read all lines:** The output is “IndiGo 90”, “Air India 90”, “IndiGo 90”.
**Answer: A — Lines: IndiGo 90; Air India 90; IndiGo 90.**
A: **Correct:** It correctly combines the shallowly shared array with the separate cloned object’s airline field.
B: **Incorrect:** The shared array means no involved object retains the old index-one value 60.
C: **Incorrect:** a3 aliases a1, so a3.airline reassignment changes a1’s airline to IndiGo.
D: **Incorrect:** Both the aliased name and shared array have changed, so these old values cannot remain.
**1. Process the valid team:** analyzeMatch("Team Tigers") takes the nonempty branch and prints “Analyzing performance for Team Tigers”.
**2. Wrap the failing call:** The empty string triggers MatchDataException("Corrupted match data"). The method catches it, creates PerformanceAnalysisException("Analysis failed"), records the first exception with initCause(e), and throws the wrapper.
**3. Read the outer catch:** e.getMessage() returns the wrapper message “Analysis failed”. e.getCause().getMessage() returns “Corrupted match data”, so the final line starts “Reason: ” followed by that original message.
**Answer: A — Lines: Analyzing performance for Team Tigers; Analysis failed; Reason: Corrupted match data.**
A: **Correct:** It includes the first successful analysis and then prints the wrapper message and its stored cause.
B: **Incorrect:** It swaps the outer message and cause and omits the first successful output.
C: **Incorrect:** It omits both the initial success line and the wrapper’s message.
D: **Incorrect:** It has the two exception-related lines but omits the first successful analysis line.
**1. Identify qualifying people:** The inclusive predicate is bmi>=18 && bmi<=25. It keeps Arjun(22.5), Meera(18.0) and Sara(24.8), while excluding Rahul(27.3), Imran(30.2) and David(17.5).
**2. Preserve Person objects:** filter keeps matching Person elements for the later p.name access. map with a Boolean predicate instead transforms each Person into a Boolean, which has no name field.
**3. Compare valid filtering forms:** One filter containing both conditions and two successive filters each containing one condition produce the same intersection. Both retain the original encounter order and print Arjun,Meera,Sara.
**Answer: C, D — C and D — both filter-based implementations.**
A: **Incorrect:** map produces Boolean elements, so the following p.name access does not compile.
B: **Incorrect:** Its second stage also maps each retained Person to Boolean, invalidating p.name.
C: **Correct:** The single filter expresses the correct inclusive interval and retains Person elements.
D: **Correct:** Successive lower-bound and upper-bound filters implement the same inclusive interval.
**1. Trace safe counting:** With an initially empty map and input [1,1,2,3], each absent key must first receive count one. The second occurrence of one then increments its count to two.
**2. Check C and D:** getOrDefault(i,0)+1 handles both first and later occurrences. The containsKey branch in D explicitly performs the same initialization-or-increment logic. Both give mappings 1→2,2→1,3→1.
**3. Reject the other operations:** A passes an integer expression where merge needs a remapping function. B calls m.get(i)+1 on an absent key, causing null unboxing and NullPointerException.
**4. Interpret printed order:** The mappings are correct, but HashMap does not specify iteration order. The sample order 1,2,3 is common for these small integer keys in the runtime used, not a contractual ordering guarantee.
**Answer: C, D — C and D — correct frequency maps.**
**Convention note:** These options compute the required counts. Exact HashMap iteration order is unspecified; sorted output would require TreeMap or explicit key sorting, and first-insertion order would require LinkedHashMap.
A: **Incorrect:** merge’s third argument must be a compatible remapping function, not the integer m.get(i)+1; the snippet does not compile.
B: **Incorrect:** The first get on a missing key returns null, whose unboxing for +1 throws NullPointerException.
C: **Correct:** getOrDefault supplies zero before the first occurrence and increments existing counts afterward.
D: **Correct:** containsKey distinguishes initialization from incrementing and produces the correct frequency map.