ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
enum Size { S; public String toString() { return "small"; } }
// in main:
System.out.print(Size.S + " " + Size.S.name() + " ");
System.out.print(Size.valueOf("small"));- A. "small S " is printed, then IllegalArgumentException is thrown
- B. small S small
- C. S S S
- D. "small small " is printed, then IllegalArgumentException is thrown
Correct answer: A. "small S " is printed, then IllegalArgumentException is thrown
Overriding toString changes how the constant prints, but name() is final and always returns the declared identifier, and valueOf looks up by that name, so "small" is not found.
More OOP with C++ and Java questions
- What is printed? java Object o = new int[]{1}; System.out.print((o instanceof int[]) + " " + (o instanceof Object[]));
- Which line fails to compile? java class P { void run() throws java.io.IOException { } } class C extends P { @Override void run() { } } //…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.put("a", 1); m.keySet().remove("a"); System.out.print(m.size() + " ")…
- What is printed? java TreeSet<Integer> s = new TreeSet<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); SortedSet<Integer> sub = s.subSet(3, 6)…
- What is printed? java List<String> l = Arrays.asList("b", null, "a"); l.sort(Comparator.nullsFirst(Comparator.naturalOrder()))…
- What is printed? java // static method of the main class: static String make() { System.out.print("M"); return "y"; } // in main…