1Z0-805 | A Review Of Practical 1Z0-805 examcollection


Q21. Given: 

public class MyGrades { 

private final List<Integer> myGrades = new ArrayList<Integer>(); 

private final ReadWriteLock rwlock = new ReentrantReadWriteLock(); 

public void addGrade(Integer grade) { 

// acquire _______ lock 

myGrades.add(grade); 

// release __________ lock 

public void averageGrades() { 

// acquire _______ lock Line ** 

double sum = 0; 

int i = 0; 

for (i = 0; i < myGrades.size(); i++) { 

sum += myGrades.get(i); 

// release __________ lock Line *** 

System.out.println("The average is: " + sum/(i+1)); 

Which pair’s statements should you insert at lines ** and lines *** (respectively) to acquire and release the most appropriate lock? 

A. rwlock.readLock().acquire(); rwlock.readLock().release(); 

B. rwlock.readLock().lock(); rwlock.readLock().unlock(); 

C. rwlock.getLock().acquire(); rwlock.getLock().release(); 

D. rwlock.getLock().lock(); rwlock.getLock().Unlock(); 

E. relock.WriteLock().acquire(); rwlock.writeLock().release(); 

F. rwlock.writeLock().lock(); rwlock.WriteLock().unlock(); 

Answer:

Explanation: We need a read lock, not a write lock, we are just reading data, not 

writing/updating data. 

To aquire and release the lock the method lock() and unlock are used. 

Reference: Class ReentrantReadWriteLock 

Q22. Consider the following database table: 

Inventory Table 

* Item_ID, Integer: PK 

* Item_name, Varchar (20) 

* Price, Numeric (10, 2) 

* Quan, Integer 

Consider the following method that updates the prices in the Inventory table: 

public static void updatePrices{ // #1: missing line 

Connection con) throws SQLException { 

// #2: missing line 

PreparedStatement updatePrices = con.prepareStatement (updatePricesString); 

// #3: missing line { // #4: missing line updatePrices.executeUpdate(); } } 

This method us missing four lines, which group of lines complete this method? 

A. 1. HashMap<Integer, String> newPrices, 

2. StringupdatePriceString = "UPDATE inventory SET price =? WHERE item_name '?' "; 

3. For (map.Entry<Integer, String> x : newPrices.entrySet()) 

4. UpdatePrices.setFloat(1, x.getvalue().floatValue()); updatePrice.setString (2, x.getKey()); 

B. 1. HashMap<Integer, Float> newPrices, 

2. StringupdatePriceString = "UPDATE inventory SET price =? WHERE item_id '?' "; 

3. For (map.Entry<Integer, String> x : newPrices.entrySet()) 

4. UpdatePrices.setFloat(1, x.getvalue().floatValue()); updatePrice.setString (2, x.getKey().intValue()); 

C. 1. HashMap<Integer, Float> newPrices, 

2. StringupdatePriceString = “UPDATE inventory SET price =? Where item_id ‘?’ ”; 

3. For (map.Entry<Integer, String> x : newPrices.entrySet()) 

4. UpdatePrices.setInt(1, x.getvalue().floatValue()); updatePrice.setString (2, x.getvalue()); 

D. 1. HashMap<Integer, Float> newPrices, 

2. StringupdatePriceString = “UPDATE inventory SET price =? Where item_id ‘?’ ”; 

3. For (map.Entry<Integer, String> x : newPrices.entrySet()) 

4. UpdatePrices.setInt(1, x.getvalue().floatValue()); updatePrice.setString (2, x.getvalue().floatValue() 

E. 1. HashMap<Integer, String> newPrices, 

2. StringupdatePriceString = “UPDATE inventory SET price =? Where item_id ‘?’ ”; 

3. For (map.Entry<Integer, String> x : newPrices.entrySet()) 

4. UpdatePrices,setString(1, x.getKey()); updatePrices.setFloat(2, x.getValue().floatValue()); 

F. 1. HashMap<Integer> newPrices, 

2. StringupdatePriceString = “UPDATE inventory SET price =? Where item_id ‘?’ ”; 

3. For (Integer x: newPrice) 

4. updatePrice.setInt(1, x); 

Answer:

Explanation: The first line should be HashMap<Integer, Float> newPrices, as in SQL numeric represent a float number, not an integer or string. We also make sure to use floatValue() both in appropriate places in line 4. 

Note: Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. 

Q23. Given the code fragment: 

SimpleDateFormat sdf; 

Which code fragment displays the two-digit month number? 

A. sdf = new SimpleDateFormat ("mm", Locale.UK); System.out.printIn ( “Result: ” + sdf.format(new Date())) 

B. sdf = new SimpleDateFormat ("MM", Locale.UK); System.out.printIn ( “Result: ” + sdf.format(new Date())) 

C. sdf = new SimpleDateFormat ("MMM", Locale.UK); System.out.printIn ( "Result: " + sdf.format(new Date())) 

D. sdf = new SimpleDateFormat ("MMMM", Locale.UK); System.out.printIn ( "Result: " + sdf.format(new Date())) 

Answer:

Explanation: B: Output example (displays current month numerically): 04 

Note: SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either getTimeInstance, getDateInstance, orgetDateTimeInstance in DateFormat. Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. 

Q24. Given the following incorrect program: 

class MyTask extends RecursiveTask<Integer> { 

final int low; 

final int high; 

static final int THRESHOLD = /* . . . */ 

MyTask (int low, int high) { this.low = low; this.high = high; } 

Integer computeDirectly()/* . . . */ 

protected void compute() { 

if (high – low <= THRESHOLD) 

return computeDirectly(); 

int mid = (low + high) / 2; 

invokeAll(new MyTask(low, mid), new MyTask(mid, high)); 

Which two changes make the program work correctly? 

A. Results must be retrieved from the newly created MyTask Instances and combined. 

B. The THRESHOLD value must be increased so that the overhead of task creation does not dominate the cost of computation. 

C. The midpoint computation must be altered so that it splits the workload in an optimal manner. 

D. The compute () method must be changed to return an Integer result. 

E. The computeDirectly () method must be enhanced to fork () newly created tasks. 

F. The MyTask class must be modified to extend RecursiveAction instead of RecursiveTask. 

Answer: A,D 

Explanation: D: the compute() method must return a result. 

A: These results must be combined (in the line invokeAll(new MyTask(low, mid), new MyTask(mid, high));) 

Note 1: A RecursiveTask is a recursive result-bearing ForkJoinTask. 

Note 2: The invokeAll(ForkJoinTask<?>... tasks) forks the given tasks, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown. 

Note 3: Using the fork/join framework is simple. The first step is to write some code that performs a segment of the work. Your code should look similar to this: 

if (my portion of the work is small enough) do the work directly else split my work into two pieces invoke the two pieces and wait for the results Wrap this code as a ForkJoinTask subclass, typically as one of its more specialized types RecursiveTask(which can return a result) or RecursiveAction. 

Q25. Given: 

public class TemperatureSensor { 

public TemperatureSensor () { 

public double getCurrTemp () { 

// . . . method to retrieve temperature from a sensor 

Return temp; 

Which three changes should you make to apply the singleton design pattern to this class? 

A. Make the class abstract. 

B. Add a method to return a singleton class type. 

C. Change the access of the constructor to private. 

D. Add a public constructor that takes a single argument. 

E. Change the class to implement the singleton interface. 

F. Add a private static final variable that is initialized to new TemperatureSensor{}; 

G. Add a public static method that returns the class variable of type 

Answer: C,F,G 

Explanation: C: We provide a default Private constructor F, G: We write a public static getter or access method (G) to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) (F) and the hence the same referenced object is returned. Note: Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. The class’s default constructor is made private (C), which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object. 

Q26. Given the following code fragment: public class Calc { 

public static void main (String [] args) { 

//* insert code here Line ** 

System.out.print("The decimal value is" + var); 

Which three code fragments, when inserted independently at line **, enable the code to compile/ 

A. int var = 0b_1001; 

B. long var = 0b100_01L; 

C. float var = 0b10_01; 

D. float var = 0b10_01F; 

E. double var = 0b10_01; 

F. double var = 0b10_01D; 

Answer: B,C,E 

Explanation: B: output 17 

C: output 9.0 

E: output 9.0 

Not A: A _ character cannot begin a number. 

Not D: A float cannot be defined as a binary number (with literal B) 

Not F: A float cannot be defined as a decimal number (with literal D) 

Note 1: 

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere 

between digits in a numerical literal. This feature enables you, for example. to separate 

groups of digits in numeric literals, which can improve the readability of your code. 

For instance, if your code contains numbers with many digits, you can use an underscore 

character to separate digits in groups of three, similar to how you would use a punctuation 

mark like a comma, or a space, as a separator. 

You can place underscores only between digits; you cannot place underscores in the 

following places: 

* At the beginning or end of a number (not A) 

* Adjacent to a decimal point in a floating point literal 

* Prior to an F or L suffix 

* In positions where a string of digits is expected 

Note 2: An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1. 

Values of the integral types byte, short, int, and long can be created from int literals. Values of type long that exceed the range of int can be created from long literals. Integer literals can be expressed by these number systems: 

Decimal: Base 10, whose digits consists of the numbers 0 through 9; this is the number system you use every day Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later) 

Reference: The Java Tutorials, Primitive Data Types: 

Using Underscore Characters in Numeric Literals 

Integer Literals 

Q27. Which two fragments can be combined into a statement that returns an ExecuteService instance? 

A. Executors 

B. Executor 

C. ExecutorService 

D. .getSingleThreadExecutor (); 

E. .newSingleThreadExecutor (); 

F. .createSingleThreadExecutor (); 

G. .buildSingleThreadExecutor (); 

Answer: A,E 

Explanation: The Executors.newSingleThreadExecutor() method creates an Executor that uses a single worker thread operating off an unbounded queue. 

Reference: java.util.concurrent.Executors 

Q28. Given the code fragment: 

dataFormat df; 

Which statement defines a new DataFormat object that displays the default date format for the UK Locale? 

A. df = DateFormat.getDateInstance (DateFormat.DEFAULT, Locale(UK)); 

B. df = DateFormat.getDateInstance (DateFormat.DEFAULT, UK); 

C. df = DateFormat.getDateInstance (DateFormat.DEFAULT, Locale.UK); 

D. df = new DateFormat.getDataInstance (DataFormat.DEFAULT, Locale.UK); 

E. df = new DateFormat.getDateInstance (DateFormat.DEFAULT, Locale(UK)); 

Answer:

Explanation: DateFormat is an abstract class that provides the ability to format and parse 

dates and times. The getDateInstance() method returns an instance of DateFormat that 

can format date information. It is available in these forms: 

static final DateFormat getDateInstance( ) 

static final DateFormat getDateInstance(int style) 

static final DateFormat getDateInstance(int style, Locale locale) 

The argument style is one of the following values: DEFAULT, SHORT, MEDIUM, LONG, or 

FULL. These are int constants defined by DateFormat. 

Q29. Which method or methods should you implement to create your own implementation of the java.nio.file.PathMatcher interface? 

A. matches(Path) 

B. matches(Path), fails(Path) 

C. matches(Path) , fails(Path), enable(boolean) 

D. matches(Path) , fails(Path) , setPreferred (String) 

Answer:

Explanation: The interface PathMatcher is an interface that is implemented by objects that 

perform match operations on paths. 

The single method for this interface is matches: 

boolean matches(Path path) 

Tells if given path matches this matcher's pattern. 

Parameters: 

path - the path to match 

Returns: 

true if, and only if, the path matches this matcher's pattern. 

Reference: java.nio.file.PathMatcher 

Q30. Which two descriptions are benefits of using PreparedStatement objects over static SQL in JDBC? 

A. Conversion to native SQL 

B. Supports BLOB types on every type of database 

C. Prevention of SQL injection attacks 

D. Improved performance from frequently run SQL queries 

E. Built in support for multi database transaction semantics 

Answer: A,D 

Explanation: Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement, that you already know. 

If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead. 

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first. 

Although PreparedStatement objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. 

Reference: The Java Tutorials, Using Prepared Statements