Return to site

☕🎓JAVA CERTIFICATION QUESTION: invocation of instance method in static context

· java

Given the following class:

import java.util.Arrays;
import java.util.regex.Pattern;
public class FooBaz {
 static final Pattern PIPE_SPLITTER = Pattern.compile("\\|");
 public static void main(String[] args) {
  System.out.print(doIt("12|11|30"));
 }
 public int doIt(String s) {
  var a = PIPE_SPLITTER.splitAsStream(s)
    .mapToInt(v -> Integer.valueOf(v))
    .mapToObj(v -> new Integer[]{v % 3 == 0 ? 1 : 0, v % 5 == 0 ? 2 : 0, v})
    .reduce(new Integer[]{0, 0, 0}, (i, is) -> new Integer[]{i[0] + is[0], i[1] + is[1], i[2] + is[2]});
  return Arrays.stream(a).mapToInt(Integer::intValue).sum();
 }
}

What is the result? Choose one.

  • A. 56 is the output.
  • B. 57 is the output.
  • C. 58 is the output.
  • D. 59 is the output.
  • E. Compilation fails.

#java #certificationquestion #ocp

 

 

 

Answer: Compilation fails.

When you see an exam question that has unreasonably complex code, be sure to check for simple things first.

You won’t always find the answer there, but if checking the hard stuff is going to take a long time, it’s smart to check the easy stuff first.

In this example, the code does not in fact, compile.

The reason is simple: The static main method attempts to call the doIt method without any explicit prefix, and such an invocation can work only for a static doIt() method.

However, doIt() is an instance method and in the absence of an explicit prefix, such an invocation will fail.