ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
// static method of the main class:
static String make() { System.out.print("M"); return "y"; }
// in main:
System.out.print(Optional.of("x").orElse(make()));
System.out.print(Optional.of("x").orElseGet(() -> make()));- A. xx
- B. MxMx
- C. Mxx
- D. My x
Correct answer: C. Mxx
orElse takes an already-evaluated argument, so make() runs even though the Optional has a value. orElseGet takes a Supplier and calls it only when the Optional is empty.
More OOP with C++ and Java questions
- What is printed? java Stream<Integer> s = Stream.of(1, 2, 3); System.out.print(s.count()); System.out.print(s.count());
- What happens when this method is compiled (Java 7 or later)? java static void f() throws java.io.IOException { try { if (Math.random() <…
- What is printed? java try { System.out.print("T"); System.exit(0); } finally { System.out.print("F"); }
- What is printed? java class N { public Object clone() throws CloneNotSupportedException { return super.clone(); } } // in main: try { new…
- What is printed? java System.out.print((List.of(1, 2).hashCode() == List.of(2, 1).hashCode()) + " " + (Set.of(1, 2).hashCode() ==…
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("O"); } static void f(Object[] a) {…