Return to site

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

February 14, 2023

Given the following class:

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.