• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/20

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

20 Cards in this Set

  • Front
  • Back
Which statement is true about the take method defined in the WatchService interface?

A. Retrieves and removes the next watch key, or returns null of none are present.

B. Retrieves and removes the next watch key. If a queued key is not immediately available, the program waits for the specified wait time.

C. Retrieves and removes the next watch key: waits if no key is yet present.

D. Retrieves and removes all pending events for the watch key, returning a list of the events that were retrieved.
Answer: C
Explanation: The WatchKey take() method retrieves and removes next watch key, waiting if none are yet present.

Note: A watch service that watches registered objects for changes and events. For example a file
manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
A Watchable object is registered with a watch service by invoking its register method, returning a WatchKey to represent the registration. When an event for an object is detected the key is signaled, and if not currently signaled, it is queued to the watch service so that it can be retrieved by consumers that invoke the poll or take methods to retrieve keys and process events. Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signaled and re-queued with further events.

Reference: Interface WatchService
Given the code fragment:
private static void copyContents (File source, File target)
{
try {inputStream fis = new FileInputStream(source);
outputStream fos = new FileOutputStream (target);
byte [] buf = new byte [8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write (buf, 0, i);
}
//insert code fragment here. Line **
System.out.println ("Successfully copied");
}

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

A. }catch (IOException | NoSuchFileException e) {
System.out.println(e);
}
B. } catch (IOException | IndexOutOfBoundException e) {
System.out.println(e);
}
C. } catch (Exception | IOException | FileNotFoundException e ) {
System.out.println(e);
}
D. } catch (NoSuchFileException e ) {
System.out.println(e);
}
E. } catch (InvalidPathException | IOException e) {
System.out.println(e);
}
Answer: B,D,E
Explanation: B: Two mutually exclusive exceptions. Will work fine.
D: A single exception. Will work fine.
E: Two mutually exclusive exceptions. Will work fine.
Note: In Java SE 7 and later, a single catch block can handle more than one type of exception.
This feature can reduce code duplication and lessen the temptation to catch an overly broad
exception. In the catch clause, specify the types of exceptions that block can handle, and separate each
exception type with a vertical bar (|).

Note 2:NoSuchFileException: Checked exception thrown when an attempt is made to access a file that does not exist. InvalidPathException: Unchecked exception thrown when path string cannot be converted into a Path because the path string contains invalid characters, or the path string is invalid for other file system specific reasons.

FileNotFoundException: Signals that an attempt to open the file denoted by a specified pathname
has failed. This exception will be thrown by the FileInputStream, Fi
Which two statements are true about the walkFileTree method of the files class?

A. The file tree traversal is breadth-first with the given FileVisitor invoked for each file encountered.
B. If the file is a directory, and if that directory could not be opened, the postVisitFileFailed method is invoked with the I/O exception.
C. The maxDepth parameter’s value is the maximum number of directories to visit.
D. By default, symbolic links are not automatically followed by the method.
Answer: C,D
Explanation: C: The method walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth,
FileVisitor<? super Path> visitor)
walks a file tree.
The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited. The visitFile method is invoked for all files, including directories, encountered at maxDepth, unless the basic file attributes cannot be read, in which case the visitFileFailed method is invoked.

D:You need to decide whether you want symbolic links to be followed. If you are deleting files, for example, following symbolic links might not be advisable. If you are copying a file tree, you might want to allow it. By default, walkFileTree does not follow symbolic links.

Reference: The Java Tutorials, Walking the File Tree
Reference: walkFileTree
Which code fragments print 1?

A. String arr [] = {"1", "2", "3"};
List <? extendsString > arrList = new LinkedList <> (Arrays.asList (arr));
System.out.println (arrList.get (0));
B. String arr [] = {"1", "2", "3"};
List <Integer> arrList = new LinkedList <> (Arrays.asList (arr));
System.out.println (arrList.get (0));
C. String arr [] = {"1", "2", "3"};
List <?> arrList = new LinkedList <> (Arrays.asList (arr));
System.out.println (arrList.get (0));
D. String arr [] = {"1","2","3"};
List <?> arrList = new LinkedList <?>(Arrays.asList (arr));
System.out.println (arrList.get (0));
E. String arr [] = {"1","2","3"};
List <Integer> extendsString > arrList =new LinkedList <Integer> (Arrays.asList (arr));
System.out.println (arrList.get (0));
Answer: A,C
Explanation:
Note:You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
Given the code fragment:
public static void main(String[] args) {
String source = "d:\\company\\info.txt";
String dest = "d:\\company\\emp\\info.txt";
//insert code fragment here Line **
} catch (IOException e) {
System.err.println ("Caught IOException: " + e.getmessage();
}
Which two try statements, when inserted at line **, enable the code to successfully move the file
info.txt to the destination directory, even if a file by the same name already exists in the destination
directory?
A. try {FileChannel in = new FileInputStream(source).getChannel();
FileChannel out = new FileOutputStream(dest).getChannel ();
in.transferTo (0, in.size(), out);
B. try {Files.copy(Paths.get(source), Paths.get(dest));
Files.delete(Paths.get(source));
C. try {Files.copy(Paths.get(source), Paths.get(dest));
Files.delete(Paths.get(source));
D. try {Files.move(Paths.get(source),Paths.get(dest));
E. try {BufferedReader br = Files.newBufferedReader(Paths.get(source), Charset.forName ("UTF-
8"));
BufferedWriter bw
Answer: B,D
Explanation:
What design pattern does the Drivermanager.getconnection () method characterize?
A. DAO
B. Factory
C. Singleton
D. composition
Answer: B
Explanation: DriverManager has a factory method getConnection() that returns a Connection object

Note 1:
A factory method is a method that creates and returns new objects. The factory pattern (also known as the factory method pattern) is a creational design pattern. A factory is a Java class that is used to encapsulate object creation code. A factory class instantiates and returns a particular type of object based on data passed to the factory. The different types of objects that are returned from a factory typically are subclasses of a common parent class.
Note 2:
The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. The following are some examples of database URLs: MySQL, Java DB.
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: C
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.
Given three resource bundles with these values set for menu1: ( The default resource bundle is written in US English.)
English US resource Bundle
Menu1 = small
French resource Bundle
Menu1 = petit
Chinese Resource Bundle
Menu = 1
And given the code fragment:
Locale.setDefault (new Locale("es", "ES")); // Set default to Spanish and Spain
loc1 = Locale.getDefault();
ResourceBundle messages = ResourceBundle.getBundle ("messageBundle", loc1);
System.out.println (messages.getString("menu1"));
What is the result?
A. No message is printed
B. petit
C. :
D. Small
E. A runtime error is produced
Answer: E
Explanation: Compiles fine, but runtime error when trying to access the Spanish Resource bundle (which does not exist):

Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name messageBundle, locale es_ES
Given:
import java.util.*;

public class StringApp {
public static void main(String[] args) {
Set<String> set = new TreeSet<String>();
set.add("X");
set.add("Y");
set.add("X");
set.add("Y");
set.add("X");
Iterator<String> it = set.iterator();
int count = 0;
while (it.hasNext()) {
switch (it.next()) {
case "X":
System.out.print("X ");
break;
case "Y":
System.out.print("Y ");
break;
}
count++;
}
System.out.println("\ncount = " + count);
}
}

What is the result?
A. X X Y X Y
count = 5
B. X Y X Y
count = 4
C. X Y
count = s
D. X Y
count = 2
Answer: D
Explanation: A set is a collection that contains no duplicate elements. So set will include only two elements at the start of while loop. The while loop will execute once for each element. Each element will be printed.
Note:
*public interface Iterator An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.
*hasNext
public boolean hasNext()
Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)
*next
public Object next()
Returns the next element in the iteration.
Given the code fragment:
List<Person> pList = new CopyOnWriteArrayList<Person>();
Which statement is true?

A. Read access to the List should be synchronized.
B. Write access to the List should be synchronized.
C. Person objects retrieved from the List are thread-safe.
D. A Person object retrieved from the List is copied when written to.
E. Multiple threads can safely delete Person objects from the List.
Answer: C
Explanation: CopyOnWriteArrayList produces a thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the
underlying array.
Note: his is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to
synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the
iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.
Given the fragment:
public class CustomerApplication {
public static void main(String[] args) {
CustomerDAO custDao = new CustomerDAOMemoryImp1();
// . . . other methods
}
}

Which two valid alternatives to line 3 would decouple this application from a specific implementation of customerDAO?

A. CustomerDAO custDao = new customerDAO();

B. CustomerDAO custDao = (CustomerDAO) new object();

C. CustomerDAO custDao = CustomerDAO.getInstance();

D. CustomerDAO custDao = (CustomerDAO) new CustomerDAOmemoryImp1();

E. CustomerDAO custDao = CustomerDAOFactory.getInstance();
Answer: C,E
Explanation:

Note: Data Access Layer has proven good in separate business logic layer and persistent layer. The DAO design pattern completely hides the data access implementation from its clients. The interfaces given to client does not changes when the underlying data source mechanism changes. this is the capability which allows the DAO to adopt different access scheme without affecting to business logic or its clients. generally it acts as a adapter between its components and database. The DAO design pattern consists of some factory classes, DAO interfaces and some DAO classes
to implement those interfaces.
Given a resource bundle MessageBundle, what is the name of the default bundle file?

A. MessageBundle.profile
B. MessageBundle.xml
C. MessageBundle.java
D. MessageBundle.properties
Answer: D
Explanation: A properties file is a simple text file. You should always create a default properties file. The name of this file begins with the base name of your ResourceBundle and ends with the .properties suffix.

Reference: The Java Tutorials,Backing a ResourceBundle with Properties Files
Given the code fragment:
public class Test {
public static void main (String [] args) {
Path path1 = Paths.get("D:\\sys\\asm\\.\\data\\..\\..\\mfg\\production.log");
System.out.println(path1.normalize());
System.out.println(path1.getNameCount());
}
}

What is the result?

A. D:\sys\mfg\production.log
8
B. D:\\sys\\asm\\.\\data\\. . \\mfg\\production.log
6
C. D: \\sys\\asm\\.\\data\\. . \\mfg\\production.log
8
D. D: \sys\mfg\production.log
4
E. D: \\ sys\\asm\\data\\mfg\\production.log
6
Answer: A

Explanation: The normalize method removes any redundant elements, which includes any "." or "directory/.." occurrences.
ThegetNameCount method returns the number of elements in the path.Here there are 8 elements (in the redundant path).

Reference: The Java Tutorials,Path Operations
You are using a database from XY/Data. What is a prerequisite for connecting to the database using a JDBC 4.0 driver from XY/Data?

A. Use the JDBC DriverManager.loadDriver method.
B. Put the XY/data driver into the classpath of your application.
C. Create an instance of the XY/Data driver class using the new keyword.
D. Create an Implementation of DriverManager that extends the XY/Data driver
Answer: B
Explanation: First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:
* DriverManager: This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path(B). Note that your application must manually load any JDBC drivers prior to version 4.0.
* DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

Note:The JDBC Architecture mainly consists of two layers:

First is JDBC API, which provides the application-to-JDBC
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)

Note1:
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 st
Given the code fragment:

String query = "SELECT ID FROM Employee"; \\ Line 1
try (Statement stmt = conn.CreateStatement()) { \\ Line 2
ResultSet rs = stmt.executeQuery(query); \\ Line 3
stmt.executeQuery ("SELECT ID FROM Customer"); \\ Line 4
while (rs.next()) {
\\process the results
System.out.println ("Employee ID: " + rs.getInt("ID") );
}
} catch (Exception e) {
system.out.println ("Error");
}

Assume that the SQL queries return records. What is the result of compiling and executing this code fragment?

A. The program prints employees IDs.
B. The program prints customer IDs.
C. The program prints Error.
D. Compilation fails on line 13.
Answer: A
Explanation: Line 3 sets the resultset rs. rs will contain IDs from the employee table. Line 4 does not affect the resultset rs. It just returns a resultset (which is not used).

Note:
A ResultSet object is a table of data representing a database result set, which is usually generated by executing a statement that queries the database.
You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet. Initially, the cursor is positioned before the first row. The method ResultSet.next moves the cursor to the next row. This method returns false if the cursor is positioned after the last row. This method repeatedly calls the ResultSet.next method with a while loop to iterate through all the data in the ResultSet.

Reference: The Java Tutorials,Retrieving and Modifying Values from Result Sets
Given:
public class SampleClass {
public static void main(String[] args) {
SampleClass sc = new SampleClass();
sc.processCD();
}
private void processCD() {
try (CDStream cd = new CDStream()) {
cd.open();
cd.read();
cd.write("lullaby");
cd.close();
} catch (Exception e) {
System.out.println("Exception thrown");
}
}

class CDStream {
String cdContents = null;
public void open() {
cdContents = "CD Contents";
System.out.println("Opened CD stream");
}
public String read() throws Exception {
throw new Exception("read error");
}
public void write(String str) {
System.out.println("CD str is: " + str);
}
public void close() {
cdContents = null;
}

What is the result?

A. Compilation CD stream
B. Opened CD thrown
C. Exception thrown
D. Opened CD stream
CD str is: lullaby
Answer: A

Explanation: In this example the compilation of line " try (CDStream cd = new CDStream()) {" will fail, as try-with-resources not applicable to variable type CDStream.

Note: The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-withresources
statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Reference: The Java Tutorials,The try-with-resources Statement
Two companies with similar robots have merged. You are asked to construct a new program that allows the features of the robots to be mixed and matched using composition. Given the code fragments:

public class CrusherRobot {
public void walk () {}
public void positionArm (int x, int y, int z) {}
public void raiseHammer() {}
public void dropHammer() {}
}
public class GripperRobot {
public void walk() {}
public void moveArm (int x, int y, int z) {}
public void openGripper () {}
public void closeGripper() {}
}

When applying composition to these two classes, what functionality should you extract into a new class?

A. A new BasicRobot class that provides walking.
B. A new BasicRobot class that combines gripping and hammering.
C. A new BasicRobotFactory class to construct instances of GripperRobot.
D. A new BasicRobotFactory class to construct instances of CrusherRobot
Answer: B
Which three must be used when using the Java.util.concurrent package to execute a task that returns a result without blocking?

A. ExecutorService
B. Runnable
C. Future
D. Callable
E. Thread
F. Executor
Answer: A,D,F
Explanation: The java.util.concurrent package defines three executor interfaces:
*(F)Executor, a simple interface that supports launching new tasks.
*(A)ExecutorService, a subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the executor itself.
* ScheduledExecutorService, a subinterface of ExecutorService, supports future and/or periodic execution of tasks.
Typically, variables that refer to executor objects are declared as one of these three interface types, not with an executor class type.
D: The ExecutorService interface supplements execute with a similar, but more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value.

Reference: The Java Tutorials,Executor Interfaces
Which statement creates a low-overhead, low contention random number generator that is isolated to a thread to generate a random number between 1 and 100?

A. int i = ThreadLocalRandom.current().nextInt (1, 101);
B. int i = ThreadSaferandom.current().nextInt(1, 101);
C. int i = (int) Math.random()*.nextInt(1, 101);
D. int i = (int) Match.random (1, 101);
E. int i = new Random (). nextInt (100)+1;
Answer: A
Explanation: public class ThreadLocalRandom
extendsRandom
A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use ofThreadLocalRandom rather thanshared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools. Usages of this class should typically be of the
form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.
This class also provides additional commonly used bounded random generation methods.