Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
What is printed? (Java: == vs equals on Strings)
What is printed? (Java: == vs equals on Strings)
String a = "hello";
String b = "hel" + "lo";
String c = new String("hello");
String d = c.intern();
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c) + " " + (a == d));- A. true true true true
- B. false false true true
- C. true false true true
- D. true false true false
Correct answer: C. true false true true
"hel" + "lo" is a compile-time constant, so it refers to the same pooled literal as a. new String creates a distinct object (== false, equals true). intern() returns the pooled instance, so a == d. Always compare contents with equals.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (expected probes in a hash table) python alpha = 0.75 chaining = 1 + alpha / 2 linearhit = 0.5 (1 + 1 / (1 - alpha))…
- What is printed? (reverse a sublist of a linked list between positions m and n, 1-based) python def revbetween(a, m, n): a = a[:] a[m…
- What is printed? (min-heap array after inserts) python import heapq h = [] for x in [9, 4, 7, 1, 8, 2]: heapq.heappush(h, x) print(h…
- What is printed? (queue using a fixed array without wrap-around) python N = 4; q = [None] N; front = rear = 0; log = [] def enq(x): global…
- A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack…
- A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed? python from collections…