Return to site

☕🎓JAVA CERTIFICATION QUESTION: ServiceLoader

· 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 = ServiceLoader.services(MyService.class).getFirstInstance();

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

#java #certificationquestion #ocp

https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

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 "ServiceLoader.services(MyService.class).getFirstInstance();"

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().