• 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 code fragment is required to load a JDBC 3.0 driver?

A. DriverManager.loadDriver(“org.xyzdata.jdbc.network driver”);
B. Class.forname (“org.xyzdata.jdbc.NetWorkDriver”);
C. Connection con = Connection.getDriver
(“jdbc:xyzdata: //localhost:3306/EmployeeDB”);
D. Connection con = Drivermanager.getConnection
(“jdbc:xyzdata: //localhost:3306/EmployeeDB”);
Answer: B

Explanation: Note that your application must manually load any JDBC drivers prior to version 4.0. The simplest way to load a driver class is to call the Class.forName() method. If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName().
What statement is true about thread starvation?

A. Thread "A" is said to be starved when it is frequently unable to gain access to a resource that it shares with another thread.
B. Thread "A" is said to be starved when it is blocked waiting for Thread "13," which in turn waiting for Thread "A."
C. Starvation can occur when threads become so busy responding to other threads that they move forward with their other work.
D. When some of the processors in a multi-processor environment go offline and the live thread(s) blocked waiting for CPU cycles, that blocking is referred to as "thread starvation."
Answer: A
Explanation: Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Reference: The Java Tutorials,Starvation and Livelock
Given the code fragment:
static void addContent () throws Exception {
Path path = Paths.get("D:\\company\\report.txt");
UserPrincipal owner =
path.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("Bob");
Files.setOwner(path, owner);
// insert code here – Line **
br.write("this is a text message ");
}
System.out.println("success");
}

Assume that the report.txt file exists.

Which try statement, when inserted at line **, enables appending the file content without writing the metadata to the underlying disk?

A. try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName ("UTF-8"), new openOption []
{StandardOpenOption.CREATE, StandardOpenOption.Append, StandardOpenOption.DSYNC}};}
{
B. try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName ("UTF-8"), new openOption [] {StandardOpenOption.APPEND, StandardOpenOption.SYNC));){

C. try (BufferWriter br = Files.newBufferedWriter (path, Charset.forName ("UTF - 8"), new
openOpt
Answer: C
Explanation: StandardOpenOption should be both APPEND (if the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning)and DSYNC (Requires that every update to the file's content be written synchronously to the underlying storage device.).

Note 1:The newBufferedWriter method Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. The options parameter specifies how the the file is created or opened. If no options are present then this
method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an
existing regular-file to a size of 0 if it exists.

Note2: public static final StandardOpenOption APPEND
If the file is opened for WRITE access then bytes will be written to the end of the file rather than the beginning.
If the file is opened f
Which two statements are true?

A. Implementing a DAO often includes the use of factory.
B. To be implemented properly, factories rely on the private keyword.
C. Factories are an example of the OO principle "program to an interface."
D. Using factory prevents your replication from being tightly coupled with a specific Singleton
E. One step in implementing a factory is to add references from all the classes that the factory will
merge.
Answer: A,C
Explanation: A: 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.

C: The essence of the Factory method Pattern is to "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory
method lets a class defer instantiation to subclasses."
Note:The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products)
without specifying the exact clas
Which five items are provided by the Java concurrency utilities?

A. High-performance, flexible thread pools
B. Dynamic adjustment of thread priorities
C. Collection classes designed for concurrent access
D. Atomic variables
E. synchronized wrappers for collection classes in the java.util package,
F. Asynchronous execution of tasks
G. Counting semaphores
H. Concurrent collection sorting implementations
Answer: A,C,D,E,G
Explanation: The Java 2 platform includes a new package of concurrency utilities. These are classes that are designed to be used as building blocks in building concurrent classes or applications. Just as thecollections framework simplified the organization and manipulation of inmemory data by providing implementations of commonly used data structures, the concurrency utilities simplify the development of concurrent classes by providing implementations of building blocks commonly used in concurrent designs. The concurrency utilities include a high performance, flexible thread pool; a framework for asynchronous execution of tasks; a host of
collection classes optimized for concurrent access; synchronization utilities such as counting semaphores (G); atomic variables; locks; and condition variables.

The concurrency utilities includes:
* Task scheduling framework. The Executor interface standardizes invocation, scheduling, execution, and control of asynchronous tasks according to a set of
Given:
import java.io.*;
public class SampleClass {
public static void main(String[] args) throws IOException {
try {
String dirName = args[0];
File dir = new File(dirName);
File.createTempFile("temp", "log", dir);
} catch (NullPointerException | IOException e) {
e = new IOException("Error while creating temp file");
throw e;
}
}
}
Answer: A

Explanation: The multi-catch parameter e may not be assigned. The compilation will fail at line:
e = new IOException("Error while creating temp file");
Given a language code of fr and a country code of FR, while file name represents a resource bundle file name that is not the default?

A. MessageBundle_fr_FR.properties
B. MessageBundle_fr_FR.Profile
C. MessageBundle_fr_FR.Xml
D. MessageBundle_fr_FR.Java
E. MessageBundle_fr_FR.locale
Answer: A

Explanation: A properties file is a simple text file. You can create and maintain a properties file with just about any text editor.
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.

To support an additional Locale, your localizers will create a new properties file that contains the translated values. No changes to your source code are required, because your program references the keys, not the values.

For example, to add support for the German language, your localizers would translate the values in LabelsBundle.properties and place them in a file named LabelsBundle_de.properties. Notice
that the name of this file, like that of the default file, begins with the base name LabelsBundle and ends with the .properties suffix.

Reference: The Java Tutorials,Backing a ResourceBundle with Properties Files
Given:
Person
public Person(int id)
public int getid()
public String getContactDetails()
public void setContactDetails(String contactDetails)
public String getName()
public void setName(String name)
public Person getPerson(int id) throws Exception
public void createPerson(int id) throws Exception
public Person deletePerson(int id) throws Exception
public void updatePerson(Person p) throws Exception

Which group of methods is moved to a new class when implementing the DAO pattern?

A. public int getId ()
public String getContractDetails ()
public void setContactDetails (String ContactDetails)
public void getName ()
public Person setName (String name)

B. public int getId ()
public String getContractDetails ()
public void getName ()
public person getPerson (int id) throws Exception

C. public void setContactDetails(String contactDetails)
public void setName (String name)

D. public person getPerson(int id) throws Exception
public void createPerson (person p) throws exception
publ
Answer: D

Explanation: We move the most abstract highest level methods into a separate class.

Note: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)
Given the code fragment:

SimpleDateFormat sdf = new SimpleDateFormat("zzzz", Locale.US);
System.out.println ("Result: " + sdf.format(today) ) ;

What type of result is printed?

A. Time zone abbreviation
B. Full-text time zone name
C. Era
D. Julian date
E. Time of the Epoch (in milliseconds
Answer: A
Explanation: Assuming that the variable today contains a date, the time zone abbreviation, such as Pacific Standard Time or Central European Summer Time, will be printed.
The advantage of a CallableStatement over a PreparedStatement is that it:

A. Is easier to construct
B. Supports transactions
C. Runs on the database
D. Uses Java instead of native SQL
Answer: C
Explanation: A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set.

There are three different kinds of statements:
* Statement: Used to implement simple SQL statements with no parameters.
* PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that might contain input parameters.
* CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that may contain both input and output parameters.
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of operations or queries to execute on a database
server.

Reference: The Java Tutorials:
Executing Queries
Using Stored Procedures
Given:
class Fibonacci extends RecursiveTask<Integer> {
final int n;
Fibonacci (int n) { this.n = n }
Integer compute () {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci (n – 1);
f1.fork;
Fibonacci f2 = new Fibonacci (n – 2);
return f2.compute() + f1.join; // Line **
}
}

Assume that line ** is replaced with:
return f1.join() + f2.compute(); // Line **
What is the likely result?

A. The program produces the correct result, with similar performance to the original.
B. The program produces the correct result, with performance degraded to the equivalent of being single-threaded.
C. The program produces an incorrect result.
D. The program goes into an infinite loop.
E. An exception is thrown at runtime.
F. The program produces the correct result, with better performance than the original.
Answer: B
Explanation: Changing the code is not useful. In the original code (return f2.compute() + f1.join; ) f1 and f2 are run in parallel. The result is joined. With the changed code (return f1.join() + f2.compute();) f1 is first executed and finished, then is f2 executed.

Note 1:The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executingt.join(); causes the current thread to pause execution until t's thread terminates.

Note 2:New in the Java SE 7 release, the fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

As with any ExecutorService, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a wor
Given:
public static void main(String[] args) throws Exception {
try {
processFile();
} catch(Exception e) {
Throwable [] t = e.getSuppressed();
}
}
public static void processFile() throws IOException {
try (FileReader fr = new FileReader"logfilesrc.txt");
FileWriter fw = new FileWriter("logfiledest.txt")) {{
java.util.zip.ZipFile zf = new java.util.zip.ZipFile("alllogs.zip");
System.out.println("Created files for logs");
}
}
The getSuppressed method returns an array of __________.

A. Allexceptions that were thrown in the processFile method but were suppressed.
B. Exceptions suppressed because that are not declared in the throws clause.
C. Only runtime exceptions that were thrown in the processFile method but were suppressed.
D. Only runtime exceptions that were thrown in the processFile method but were not declared in throws clause.
Answer: A
Explanation: The GetSuppressed() methodreturns an array containing all of the exceptions that were suppressed, typically by the try-with-resources statement, in order to deliver this exception.
If an exception is thrown from the try block and one or more exceptions are thrown from the trywith-resources statement, then those exceptions thrown from the try-with-resources statement are
suppressed.

Reference: The Java Tutorials,Suppressed Exceptions
Given the code fragment:
11. public static getFileSize () throws IOException {
12. path file = paths.get ("ex.txt");
13. //insert code here
14. System.out.println ("size: " + attr.size());
15. }
public static getFileSize () throws IOException {
Path file = Paths.get ("ex.txt");
//insert code here Line **
System.out.println ("size: " + attr.size());
}

Which two fragments, when inserted independently at line **, enable printing of the file size?

A. BasicFileAttributes attr = Files.readAttributes (file, BasicFileAttributes.class);
B. PosixFileAttributes attr = Files.readAttributes (file, posixFileAttributes.class);
C. DosFileAttributes attr = Files.readAttributes (file, dosAttributes.class);
D. FileStore attr = Files.getFileStore (file);
E. AclFileAttributeview attr = Files.getFileAttributeView(File, AclFileAttributeview.class);
Answer: A,B
Explanation: A: The BasicFileAttributes has a size method.
B: The PosixFileAttributes has a size method.
Which two statements are true about RowSet subinterfaces?

A. A jdbcRowSet object provides a JavaBean view of a result set.
B. A cachedRowSet provides a connected view of the database.
C. A FilteredRowSet object filter can be modified at any time.
D. A webRowSet returns JSON-formatted data.
Answer: A,C
Explanation: A:JdbcRowSet Mmakes results available as a JavaBean component

C: FilteredRowSetimplements lightweight querying, usingjavax.sql.rowset.Predicate The predicate set on a FilteredRowSet object applies a criterion on all rows in a RowSet object to manage a subset of rows in aRowSet object. This criterion governs the subset of rows that are visible and also defines which rows can be modified, deleted or inserted. Therefore, the predicate set on a FilteredRowSet object must be considered as bi-directional and the set criterion as the gating mechanism for all views and updates to the FilteredRowSet object. Any attempt to update the FilteredRowSet that violates the criterion will result in a SQLException object being thrown. The FilteredRowSet range criterion can be modified by applying a new Predicate object to
the FilteredRowSet instance at any time. This is possible if no additional references to the FilteredRowSet object are detected. A new filter has has an immediate effect on cr
Consider the following five methods:

public Connection getConnetionA( String userName, String password, String dbName) throws Exception {
Properties connectionProps = new Properties();
connectionProps.Props("user", userName);
connectionProps.Props("password", password);
DriverManager.registerDriver(new org.xyzdata.jdbc.EmbeddedDriver());
return DriverManager.getConnection("jdbc:xyzdata:" + dbName, connectionProps);
}

public Connection getConnectionB(String dbName) throws Exception {
Class.forName("org.xyzdata.jdbc.EmbeddedDriver");
return DriverManager.getConnection("jdbc:xyzdta:" + dbName);
}

public Connection getConnectionC(String userName, String password, String dbName) throws Exception {
Class.forName("org.xyzdata.jdbc.NetwordKriver").newInstance();
return DriverManager.getConnection("jdbc:xyzdata:" + dbName + ";user="+username + ";password=" + password);
}

public Connection getConnectionD(String userName, String password, String dbName) throws Exceptio
Answer: D
Explanation: Note on D not E: Prior to JDBC 4.0, we relied on the JDBC URL to define a data source connection. Now with JDBC 4.0, we can get a connection to any data source by simply supplying a set of parameters (such as host name and port number) to a standard connection factory mechanism. New methods were added to Connection and Statement interfaces to permit improved connection state tracking and greater flexibility when managing Statement objects in pool environments.

Note on that an embedded driver is no longer needed(not A, B, C):
Thanks to the Java SE Service Provider mechanism included in Mustang, Java developers no longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC
driver. The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no
changes are needed to the existing JDBC code.

In JDBC 4.0, we no longer need to
Given the code fragment:
public static void main(String[] args) {
Path dir = Paths.get("d:\\company");
// insert code here. Line **
for (Path entry: stream) {
System.out.println(entry.getFileName());
}
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
}

Which two try statements, when inserted at line 11, enable you to print files with the
extensions.java, .htm, end and .jar.
A. try (DirectoryStream&lt;path> stream =Files.newDirectoryStream(dir, "*.{java, htm, jar}")) {
B. try (DirectoryStream&lt;path> stream =Files.newDirectoryStream(dir, "*.[java, htm, jar"] }} {
C. try (DirectoryStream&lt;path> stream =Files.newDirectoryStream(dir, "*.{java*, htm*, jar*}"}} {
D. try (DirectoryStream&lt;path> stream =Files.newDirectoryStream(dir, "**.{java, htm, jar}")) {
Answer: A,D
Reference: The Java Tutorials
Finding Files
What Is a Glob?
Given the code fragment:
Locale loc1 = Locale.getDefault ();
ResourceBundle messages = ResourceBundle.getBundle("MessageBundle", loc1);

Which two statements are a valid way to re-assign a resource bundle to a different Locale?

A. loc1 = ResourceBundle.getBundle ("MessageBundle", Locale.CHINA);
B. loc1 = ResourceBundle.getBundle ("MessageBundle", new Locale ("es", "ES"));
C. messages = ResourceBundle.getBundle ("messageBundle", new Locale ("es", "ES"));
D. messages = ResourceBundle.getBundle ("MessageBundle", Locale.CHINA);
Answer: C,D
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 patternbelongs 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
Given the error message when running you application:

Exception in thread “main” java.util.MissingResourceException: can’t find bundle for base name messageBundle, Locale

And given that the Message Bundle.properties file has been created, exists on your disk, and is properly formatted. What is the cause of the error message?

A. The file is not in the environment PATH.
B. The file is not in the CLASSPATH.
C. The file is not in the JJAVAPATH.
D. You cannot use a file to store a ResourceBundle
Answer: B
Explanation: Your language file should be in the classpath.
Which two statements are true regarding the try with resources statement?

A. The resources declared in a try with resources statement are not closed automatically if an exception occurs inside the try block.
B. In a try with resources statement, any catch or finally block is run after the resources have been closed.
C. The close methods of resources are called in the reverse order of their creation.
D. All the resources must implement the java.io.closeable interface
Answer: B,D
Explanation: B: Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.
A try-with-resources statement can have catch and finally blocks just like an ordinary trystatement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
D: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 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 implementjava.io.Closeable, can be used as a resource.

Reference: The Java Tutorials,The try-with-resources Statement