Return to site


· java,ocp

Consider the following methods to load an implementation of MyService using ServiceLoader. Which of the methods are correct? (Choose all that apply)

* MyService service = ServiceLoader.load(MyService.class).findFirst().get();

* MyService service = ServiceLoader.load(MyService.class).iterator().next();

* MyService service =;

* MyService service = ServiceLoader.getService(MyService.class);

#java #certificationquestion #ocp

Option "ServiceLoader.load(MyService.class).findFirst().get();"

is correct because it uses ServiceLoader.load() to find the first available service provider for MyService and retrieves it if present.

Option "ServiceLoader.load(MyService.class).iterator().next();"

is correct as it uses ServiceLoader.load() to get an iterator over available service providers for MyService and retrieves the next element if available.

Option ";"

is incorrect because there is no services() method in ServiceLoader class that provides a getFirstInstance() method.

Option "ServiceLoader.getService(MyService.class);"

is incorrect because ServiceLoader does not have a method named getService().