ProgrammingModerateProduct-company placement · Java
What is printed?
What is printed?
class Range implements Iterable<Integer> {
public Iterator<Integer> iterator() { return List.of(1, 2, 3).iterator(); }
}
// in main:
for (int x : new Range()) System.out.print(x);- A. Compile-time error: Range is not a collection
- B. [1, 2, 3]
- C. 123
- D. 321
Correct answer: C. 123
The enhanced for loop works with any Iterable: it calls iterator() and then hasNext/next, unboxing each Integer into x.
More OOP with C++ and Java questions
- Which line fails to compile (C++17)? cpp struct A { A() = default; A(const A&) = delete; A(A&&) = default; }; A make() { A a; return a; }…
- What is printed? cpp int main() { const string s = "x"; string t = std::move(s); cout << s << t; }
- Which line fails to compile? cpp int main() { int x = 1; const int& r = x; auto a = r; // L1 a++; // L2 decltype(r) b = x; // L3 b++; //…
- Which line fails to compile? cpp struct A { virtual ~A() { } }; struct B { virtual ~B() { } }; struct C : A, B { }; int main() { A a = new…
- What does the C++ standard say about this code? cpp const int x = 5; int p = constcast<int>(&x); p = 6;
- For the call f(g(), h()) in C++17, which statement is correct?