"Java SE 8 Programmer II: Initialize Locale Variable"

"Initializing a Locale Variable: Exam 1Z0-809"

Question

Which two code blocks correctly initialize a Locale variable? (Choose two.)

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

DE.

Of the options given, the two correct code blocks to initialize a Locale variable are:

B. Locale loc2 = Locale.getInstance("ru"); E. Locale loc5 = new Locale ("ru", "RU");

Here's why:

A. Locale loc1 = "UK"; This code block is incorrect because it attempts to assign a string literal to a Locale variable. The compiler will not allow this type of assignment, and will generate an error. To create a Locale object, one of the Locale class factory methods or the constructor should be used.

B. Locale loc2 = Locale.getInstance("ru"); This code block is correct because it calls the Locale.getInstance() method to create a Locale object with the specified language code "ru". The method will automatically handle the conversion of the language code to the appropriate case, and will return a Locale object with the language set to "ru".

C. Locale loc3 = Locale.getLocaleFactory("RU"); This code block is incorrect because there is no getLocaleFactory() method in the Locale class. This is likely a typo or a misunderstanding of the Locale class methods.

D. Locale loc4 = Locale.UK; This code block is incorrect because it attempts to assign a static field of the Locale class to a Locale variable. While this is a valid way to obtain a Locale object with the language and country set to the default values for the UK, it is not a method call, and thus is not one of the correct code blocks.

E. Locale loc5 = new Locale ("ru", "RU"); This code block is correct because it creates a new Locale object with the specified language code "ru" and country code "RU". The Locale constructor takes two String arguments: the language code and the country code, in that order. By passing in "ru" and "RU", respectively, the code creates a Locale object representing the Russian language as spoken in Russia.