• 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/21

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;

21 Cards in this Set

  • Front
  • Back
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
Given:
public class DataCache {
private static final DataCache instance = new DataCache ();
public static DataCache getInstance () {
return instance;
}
}

Which design pattern best describes the class?
A. Singleton
B. DAO
C. Abstract Factory
D. Composition
Answer: A
Explanation: 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, 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.
Given the code format:

SimpleDateFormat sdf;

Which code statements will display the full text month name?

A. sdf = new SimpleDateFormat ("mm", Locale.UK);
System.out.println ( "Result: " + sdf.format(new Date()));
B. sdf = new SimpleDateFormat ("MM", Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
C. sdf = new SimpleDateFormat ("MMM", Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
D. sdf = new SimpleDateFormat ("MMMM", Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
Answer: D
Explanation: To getthe full length month name use SimpleDateFormat('MMMM').

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.
The default file system includes a logFiles directory that contains the following files:

log – Jan2009
log_01_2010
log_Feb2010
log_Feb2011
log-sum-2012

How many files the matcher in this fragment match?
PathMatcher matcher = FileSystems.getDefault ().getPathMatcher ("glob:???_*1");

A. One
B. Two
C. Three
D. Four
E. Five
F. Six
Answer: A
Explanation: The glob pattern is: any three characters, followed by _ ,followed by any number of characters, and ending with a 1.
Only log_Feb2011 matches this pattern.

Note:
You can use glob syntax to specify pattern-matching behavior.

A glob pattern is specified as a string and is matched against other strings, such as directory or file names. Glob syntax follows several simple rules:

* An asterisk, *, matches any number of characters (including none).
** Two asterisks, **, works like * but crosses directory boundaries. This syntax is generally used for matching complete paths.
* A question mark, ?, matches exactly one character.
* Braces specify a collection of subpatterns. For example:
{sun,moon,stars} matches "sun", "moon", or "stars."
{temp*,tmp*} matches all strings beginning with "temp" or "tmp."
* Square brackets convey a set of single characters or, when the hyphen character (-) is used, a range of characters. For example:
[aeiou] matches any lowercase vowel.
[0-9] mat
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: B
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.
Which three enum constants are defined in FilevisitResult?
A. CONTINUE
B. SKIP_SIBLINGS
C. FOLLOW_LINKS
D. TERMINATE
E. NOFOLLOW_LINKS
F. DELETE_CHILD
Answer: A,B,D
Explanation: The FileVisitor methods return a FileVisitResult value. You can abort the file walking process or control whether a directory is visited by the values you return in the FileVisitor methods:

* CONTINUE – Indicates that the file walking should continue. If the preVisitDirectory method returns CONTINUE, the directory is visited.
* SKIP_SIBLINGS – When preVisitDirectory returns this value, the specified directory is not visited, postVisitDirectory is not invoked, and no further unvisited siblings are visited. If returned from the postVisitDirectory method, no further siblings are visited. Essentially, nothing further happens in the specified directory.
* TERMINATE – Immediately aborts the file walking. No further file walking methods are invoked after this value is returned.
* SKIP_SUBTREE – When preVisitDirectory returns this value, the specified directory and its subdirectories are skipped. This branch is "pruned out" of the tree.

Note:To walk a file tree, you first need to
Given the code fragment:
public void processFile() throws IOException, ClassNotFoundException {
try (FileReader fr = new FileReader ("logfilesrc.txt");
FileWriter fw = new FileWriter ("logfiledest.txt")) {
Class c = Class.forName ("java.lang.JString");
}
}

If exception occur when closing the FileWriter object and when retrieving the JString class object, which exception object is thrown to the caller of the processFile method?

A. java.io.IOException
B. java.lang.Exception
C. java.lang.ClassNotException
D. java.lang.NoSuchClassException
Answer: A
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
Answer: A,D
Explanation: D: the compute() method must return a result.
A: These results must be combined (in the lineinvokeAll(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.
QUESTION NO: 28
Given:
private static void copyContents() {
try (
InputStream fis = new FileInputStream("report1.txt");
OutputStream fos = new FileOutputStream("consolidate.txt");
) {
byte[] buf = new byte[8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fis = new FileInputStream("report2.txt");
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}

What is the result?
A. Compilation fails due to an error at line 28
B. Compilation fails due to error at line 15 and 16
C. The contents of report1.txt are copied to consolidate.txt. The contents of report2.txt are appended to consolidate.txt, after a new line
D. The contents of report1.txt are copied to consolidate.txt. The contents of report2.txt are appended to consolidate.txt, without a break in the flow.
Answer: A
Explanation: The auto-closable resource fis may not be assigned.
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
How many Threads are created when passing tasks to an Executor Instance?

A. A new Thread is used for each task.
B. A number of Threads equal to the number of CPUs is used to execute tasks.
C. A single Thread is used to execute all tasks.
D. A developer-defined number of Threads Is used to execute tasks.
E. A number of Threads determined by system load is used to execute tasks.
F. The method used to obtain the Executor determines how many Threads are used to execute tasks.
Answer: F
Explanation: A simple way to create an executor that uses a fixed thread pool is to invoke the
newFixedThreadPool factory method in java.util.concurrent.Executors This class also provides the
following factory methods:
* The newCachedThreadPool method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks.
* The newSingleThreadExecutor method creates an executor that executes a single task at a time.
* Several factory methods are ScheduledExecutorService versions of the above executors.
If none of the executors provided by the above factory methods meet your needs, constructing instances of Java.util.concurrent.ThreadPoolExecutor or java.util.concurrent.ScheduledThreadPoolExecutor will give you additional options.

Note:The Executor interface provides a single method, execute, designed to be a drop-in replacementfor a common thread-creation idiom. If r is a Runnable object, and e is an Executor object you can replac
Given the code fragment:

SimpleDateFormat sdf;

Which code fragment displays the three-character month abbreviation?

A. sdf = new SimpleDateFormat ("mm", Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
B. sdf = new SimpleDateFormat (“MM”, Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
C. sdf = new SimpleDateFormat (“MMM”, Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
D. sdf = new SimpleDateFormat (“MMMM”, Locale.UK);
System.out.println ("Result:"+ sdf.format(new Date()));
Answer: C
Explanation: C: Output example: Apr

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.
Given the code fragment:
public static void processFile () throws IOException {
Try (FileReader fr = new FileReader ("logfilesrc.txt");
FileWriter fw = new FileWriter ("logfilesdst.txt") ) {
int i = fr.read();
}
}

Which statement is true?

A. The code fragment contains compilation errors.
B. The java runtime automatically closes the FileWriter Instance first and the FileReader instance next.
C. The java runtime automatically closes the FileReader Instance first and the FileWriter instance next.
D. The developer needs to close the FileReader instance first and the FileWriter instance explicitly in a catch block.
E. The Java runtime may close the FileReader and FileWriter instance in an intermediate manner. Developers should not rely on the order in which they are closed.
Answer: B

Explanation: The try-with-resources statement is a try statement that declares one or more resources. Aresource is an object that must be closed after the program is finished with it. The trywith-resources 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 implementjava.io.Closeable, can be used as a resource.

Reference: The Java Tutorials,The try-with-resources Statement
Given this code fragment:

ResultSet rs = null;
try (Connection conn = DriverManager. getConnection (url) ) {
Statement stmt = conn.createStatement();
rs stmt.executeQuery(query);
//-.. other methods }
} catch (SQLException se) {
System.out.println ("Error");
}

Which object is valid after the try block runs?
A. The Connection object only
B. The Statement object only
C. The Result set object only
D. The Statement and Result Set object only
E. The connection, statement, and ResultSet objects
F. Neither the Connection, Statement, nor ResultSet objects
Answer: C

Explanation: Generally, JavaScript has just 2 levels of scope: global and function. But, try/catch is an exception (no punn intended). When an exception is thrown and the exception object gets a variable assigned to it, that object variable is only available within the "catch" section and is
destroyed as soon as the catch completes.
View the Exhibit:

Project
|
___________________|___________________
| | |
WebJava Standalonejava Game Java
_____|___________ |
| | |
Banking java Resort java Admin java


Given the following code fragment:
class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private static int numMatches = 0;
Finder() {
matcher = FileSystems.getDefault().getPathMatcher("glob:*java");
}
void find(Path file) {
Path Name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
}
}
void report()
{
System.out.println("Matched: " + numMatches);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Answer: B

Explanation: The program will compile and run.
Referring to the exhibit there will be six nodes that matches glob:*java.
Given the following code fragment:
public static void main(String[] args) {
Path tempFile = null;
try {
Path p = Paths.get("emp");
tempFile = Files.createTempFile(p, "report", ".tmp");
try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Charset.forName("UTF8")))){
writer.write("Java SE 7");
}
System.out.println("Temporary file write done");
} catch(IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}

What is the result?

A. The report.tmp file is purged during reboot.
B. The report.tmp file is automatically purged when it is closed.
C. The report.tmp file exists until it is explicitly deleted.
D. The report.tmp file is automatically purged when the execution of the program completes.
Answer: C

Explanation: The createTempFile (String prefix,
String suffix,
FileAttribute<?>... attrs) method creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

This method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically. In this scenario no delete mechanism is specified.

Reference: java.nio.file.createTempFile
Which two Capabilities does Java.util.concurcent.BlockingQueue provide to handle operation that cannot be handled immediately?

A. Automatically retry access to the queue with a given periodicity.
B. Wait for the queue to contain elements before retrieving an element.
C. Increase the queue's capacity based on the rate of blocked access attempts.
D. Wait for space to become available in the queue before inserting an element.
Answer: B,D
Explanation: A blocking queue is a Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

Note: The BlockingQueue interface in the java.util.concurrent class represents a queue which is thread safe to put into, and take instances from. The producing thread will keep producing new objects and insert them into the queue, until the queue reaches some upper bound on what it can contain. It's limit, in other words. If the blocking queue reaches its upper limit, the producing thread is blocked while trying to insert the new object.
It remains blocked until a consuming thread takes an object out of the queue. The consuming thread keeps taking objects out of the blocking queue, and processes them. If the consuming thread tries to take an object out of an empty queue, the consuming thread is blocked until a producing thread puts an object into the queue.

Referen
Which is true regarding the java.nio.file.Path Interface?
A. The interface extends WatchService interface
B. Implementations of this interface are immutable.
C. Implement at ions of this interface arc not safe for use by multiple concurrent threads.
D. Paths associated with the default provider are not interoperable with the
Answer: A
Explanation: The java.nio.file.Path interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.

Note: An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.

A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present. The name element that is farthest from the root of the directory hierarchy is the name of a file or directory. The other name elements are directory names. A Path can represent a root, a root and a sequence of names, or simply one or more name elements. A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default
directory of the file syste
What are two benefits of a Factory design pattern?

A. Eliminates direct constructor calls in favor of invoking a method
B. Provides a mechanism to monitor objects for changes
C. Eliminates the need to overload constructors in a class implementation
D. Prevents the compile from complaining about abstract method signatures
E. Prevents tight coupling between your application and a class implementation
Answer: A,E
Explanation: Factory methods are static methods that return an instance of the native class.
Factory methods :
* have names, unlike constructors, which can clarify code.
* do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
* can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.

Note: The factory pattern (also known as the factory method pattern) is a creational design pattern. A factory is a JavaSW 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. The data passed from the calling code to the factory ca
The two methods of course rescue that aggregate the features located in multiple classes are
__________.
A. Inheritance
B. Copy and Paste
C. Composition
D. Refactoring
E. Virtual Method Invocation
Answer: C,E
Explanation: C: Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

E: In object-oriented programming, a virtual function or virtual method is
a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).
The concept of the virtual function solves the following problem:
In OOP when a derived class inherits a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behaviour is ambiguous. The distinction between virtual and non-virtual resolves this ambigui
Given:
public class DAOManager {
public AccountDAO getAccountDAO() {
return new AccountJDBCDAO();
}
}

Which design pattern best describes the class?

A. Singleton
B. DAO
C. Factory
D. Composition
Answer: B

Explanation: Data Access Object
Abstracts and encapsulates all access to a data source
Manages the connection to the data source to obtain and store data
Makes the code independent of the data sources and data vendors (e.g. plain-text, xml, LDAP,
MySQL, Oracle, DB2
Which two scenarios throw FileSystemNotFoundException when the paths.get(URI) method is invoked?

A. When preconditions on the uri parameter do not hold
B. When the provider identified by the URI’S scheme component is not installed
C. When a security manager is installed and it denies an unspecified permission to acess the file system.
D. When the file system identified by the uri does not exist and cannot be created automatically
E. When the path string cannot be converted to a Path
Answer: B,D
Explanation: The file system, identified by the URI, does not exist and cannot be created automatically, or the provider identified by the URI's scheme component is not installed.

Note: This method converts the given URI to a Path object.
It throws the following exceptions:
*IllegalArgumentException - if preconditions on the uri parameter do not hold. The format of the URI is provider specific.
*FileSystemNotFoundException - The file system, identified by the URI, does not exist and cannot be created automatically, or the provider identified by the URI's scheme component is not installed
*SecurityException - if a security manager is installed and it denies an unspecified permission to access the file system

Reference: java.nio.file.Paths