Upgrade to Java SE 7 Programmer v6.1 (1Z0-805)

Page:    1 / 6   
Total 90 questions

Given the code fragment:
public class TestString {
public static void main(String[] args) {
String str=null;
switch(str) {
case "":
System.out.println("blank"); break;
case "null":
System.out.println("NULL"); break;
default:
System.out.println("invalid"); break;
What is the result?

  • A. Compilation fails
  • B. Blank
  • C. NULL
  • D. An exception is thrown at runtime
  • E. Invalid


Answer : D

Explanation: A java.lang.NullPointerException will be thrown at runtime at line: switch(str) {
Ensure that the expression in any switch statement is not null to prevent a
NullPointerException from being thrown.
Reference: The Java Tutorials, The switch Statement

Given the code fragment:
try {
String query = "SELECT * FROM Employee WHERE ID=110";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query); // Line 13
System.out.println("Employee ID: " + rs.getInt("ID")); // Line 14
} catch (Exception se) {
System.out.println("Error");
Assume that the SQL query matches one record. What is the result of compiling and executing this code?

  • A. The code prints error.
  • B. The code prints the employee ID.
  • C. Compilation fails due to an error at line 13.
  • D. Compilation fails due to an error at line 14.


Answer : B

Explanation: Assuming that the connection conn has been set up fine, the code will compile and run fine.
Note #1: The GetInt method retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Note 2: A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only.
Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable.
Reference: The Java Tutorials, Interface ResultSet

Given the code fragment:
Path path1 = Paths.get("D:\\sales\\.\\quarterly\\..\\report"); path1 = path1.normalize();
Path path2 = path1.relativize(Paths.get("d:\\empdetails.dat")); path2 = path2.resolve(path1);
System.out.println(path1);
System.out.println(path2);
What is the result?

  • A. D: \sales\report
  • B. \sales\report
  • C. D: \sales\quarterly\ . . . \report
  • D. \sales\report
  • E. D: \sales\quarterly\ . . .\report
  • F. \sales\report\empdetails.dat
  • G. D: \sales\report
  • H. \sales\report\empdetails.dat


Answer : A

Explanation: Path1 is the normalized result of D:\\sales\\.\\quarterly\\..\\report namely D: \sales\report.
The normalize method removes any redundant elements, which includes any "." or
"directory/.." occurrences.
Consider path2.
With the relativize line path2 is set to ../../empdetails.dat
In this scenario the following applies to the resolve statement: Passing an absolute path to the resolve method returns the passed-in path. So Path2 will be set to Path1 in the statement path2 = path2.resolve(path1);
Note:
A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativizemethod. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.
You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.
Reference: The Java Tutorials, Path Operations

Given:
Which design pattern moves the getPerson, createPerson, deletePerson, and updatePerson methods to a new class?

  • A. Singleton
  • B. DAO
  • C. Factory
  • D. Composition


Answer : B

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)

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 : D

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.

Which is a key aspect of composition?

  • A. Using inheritance
  • B. Method delegation
  • C. Creating abstract classes
  • D. Implementing the composite interface


Answer : B

Explanation: In an object-oriented design of a Java program, the way in which you model objects that contain other objects is with composition, the act of composing a class out of references to other objects. With composition, references to the constituent objects become fields of the containing object.
To use composition in Java, you use instance variables of one object to hold references to other objects.
The relationship modeled by composition is often referred to as the "has-a" relationship.
Delegation involves re-exporting methods; in a composition relationship, the inner objects methods may be used only privately and not re-exposed.

Given:
What two changes should you make to apply the DAO pattern to this class?

  • A. Make the customer class abstract.
  • B. Make the customer class an interface.
  • C. Move the add, delete, find, and update methods into their own implementation class.
  • D. Create an interface that defines the signatures of the add, delete, find and update command.
  • E. Make the add, delete, find, and update methods private for encapsulation.
  • F. Make the getName and getId methods private fir encapsulation.


Answer : C,D

Explanation: In computer software, a data access object (DAO) is an object that provides an abstract interface to some type of database or persistence mechanism, providing some specific operations without exposing details of the database. It provides a mapping from application calls to the persistence layer. This isolation separates the concerns of what data accesses the application needs, in terms of domain-specific objects and data types
(the public interface of the DAO), and how these needs can be satisfied with a specific
DBMS, database schema, etc. (the implementation of the DAO).
In the specific context of the Java programming language, Data Access Objects as a design concept can be implemented in a number of ways. This can range from a fairly simple interface that separates the data access parts from the application logic, to frameworks and commercial products.

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

Given the code fragment:
/* method declaration */ {
try {
String className = "java.lang.String";
String fieldname = "somefield";
Class c = Class.forName(className);
Field f = c.getField(fieldname);
} catch(Exception e) {
e.printStackTrace();
throw e;
Which two method declarations are valid options to replace /* method declaration */?

  • A. public void getMetadata ()
  • B. public void getMetadat ()
  • C. public void getMetadata () throws Exception
  • D. public void getMetadata () throws NoSuchFieldException
  • E. public void getMetadata () throws classNotFoundException
  • F. public void getMetadata () throws ClassNotFoundException, NoSuchFieldException.


Answer : C,F

Explanation: We must specify that the getMetaData method can throw both
ClassNotFoundException (line Class c = Class.forName(className);) and a
NoSuchFieldException (line Field f = c.getField(fieldname);).
We can do this by either declare that all exception can be thrown or that these two specific exceptions can be thrown
Note: Valid Java programming language code must honor the Catch or Specify
Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:
* A try statement that catches the exception. The try must provide a handler for the exception.
* A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception.
Code that fails to honor the Catch or Specify Requirement will not compile.
Reference: The Java Tutorials, The Catch or Specify Requirement

You have been asked to create a ResourceBundle file to localize an application.
Which code example specifies valid keys of menu1 and menu2 with values of File Menu and View Menu?

  • A. <Key name = “menu1”>File Menu</Key> <Key name = “menu2”>view Menu </Key>
  • B. <Key>menu1</key><value>File Menu </value> <Key>menu2</key><value>View Menu </value>
  • C. menu1, File Menu, menu2, View Menu
  • D. menu1 = File Menu menu2 = View Menu


Answer : D

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.
An example of the contents of a ResourceBundle file:
# This is a comment
s1 = computer
s2 = disk
s3 = monitor
s4 = keyboard
Note that in the preceding file the comment lines begin with a pound sign (#). The other lines contain key-value pairs. The key is on the left side of the equal sign and the value is on the right. For instance, s2 is the key that corresponds to the value disk. The key is arbitrary. We could have called s2 something else, like msg5 or diskID. Once defined, however, the key should not change because it is referenced in the source code. The values may be changed. In fact, when your localizers create new properties files to accommodate additional languages, they will translate the values into various languages.
Reference: The Java Tutorials, Backing a ResourceBundle with Properties Files

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; // Line X
Fibonacci f2 = new Fibonacci (n 2); // Line Y
return f2.compute() + f1.join;
Suppose that lines X and Y are transposed:
Fibonacci f2 = new Fibonacci (n 2); // Line Y
f1.fork; // Line X
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, the better performance than the original.


Answer : A

Explanation: The degree of parallelism is not changed. Functionality is the same.

Given the incomplete pseudo-code for a fork/join framework applications: submit (Data) { if (Data.size < SMALL_ENOUGH) {
_________(Data); // line X
else {
List<Data> x = _________________(Data); // line Y
for(Data d: x
______________(d); // line Z
And give the missing methods:
Process, submit, and splitInHalf
Which three insertions properly complete the pseudo-code?

  • A. Insert submit at line X
  • B. Insert splitHalf at line X
  • C. Insert process at line X
  • D. Insert process at line Y
  • E. Insert splitHalf at line Y
  • F. Insert process at line Z
  • G. Insert submit at line Z


Answer : C,E,G

Explanation: C: If Data.Size is "small enough" then process it directly.
E: Else we split it in half.
G: We use a recursive submit (of the splitted Data).

The current working directory is named finance.
Which two code fragments allow you to write the salary.dat file if it does not exist under
"finance\payroll"?

  • A. public static void setFileContent (String[] s) throws IOException { path p=paths.get("payroll\\salary.dat"); File file=p.toAbsolutePath().toFile(); try (BufferWriter br = new BufferWriter (new FileWriter(File))) { br.write (experience new features of java); } }
  • B. public static void setFileContent (String[] s) throws IOException { path p=paths.get ("payroll\\salary.dat"); File file=p.toAbsolutePath(LinkOption.NOFOLLOW_LINKS).toFile(); try (BufferWriter br = new BufferWriter (new FileWriter(File))) { br.write (experience new features of java); } }
  • C. public static void setFileContent (String[] s) throws IOException { File file= new file ("payroll\\salary.dat").getCanonicalFile(); try (BufferWriter br = new BufferWriter (new FileWriter(File))) { br.write (experience new features of java); } }
  • D. public static void setFileContent (String[] s) throws IOException { File file= new File ("payroll\\salary.dat").getCanonicalFile(); try (BufferWriter br = new BufferWriter (new FileWriter(File))) { br.write (experience new features of java); } }
  • E. public static void setFileContent (String[] s) throws IOException { File file=new File ("payroll\\salary.dat").getAbsolutePath(); try (BufferWriter br = new BufferWriter (new FileWriter(File))) { br.write (experience new features of java); } }


Answer : B,D

Explanation: The problem in this scenario is how to construct a system-dependent filename from the string "payroll\\salary.dat".
Regarding File-paths:
1- A file can have many relative paths.2- Canonical paths are absolute paths.3- An absolute path is not necessarily a canonical path! This holds trueespecially under Unix, which support symbolic links. Under Windows, anabsolute path is usually a canonical path.
B: The absolute path can include symbolic links. Here we ignore them with
NOFOLLOW_LINKS option.
D: The File.getCanonicalFile Method creates a new instance of a File object representing the file located at the absolute path of the current File object. All '.' and '..' references will be resolved.

Which statement is true about the DSYNC constant defined in standardopenoptions enums?

  • A. DSYNC keeps only the file content and not the metadata synchronized with the underlying storage device.
  • B. DSYNC keeps the file (both content and metadata) synchronized with the underlying storage device.
  • C. DSYNC keeps only the file metadata and not the file content synchronized with the underlying storage device.
  • D. DSYNC keeps the file (both content and metadata) de-synchronized with copies in the und< storage device.


Answer : A

Explanation: DSYNC keeps the file content synchronized with the underlying storage device.
Note: SYNC keeps the file (both content and metadata) synchronized with the underlying storage device.
Note 2: These are from the java.nio.file.StandardOpenOption enum class.

Given the following code fragment:
public static void getInfo() {
//insert code here
List fontCatalog = new ArrayList();
fontCatalog.add("Algerian");
fontCatalog.add("Cambria");
fontCatalog.add("Lucida Bright");
category.put("firstCategory",fontCatalog);
List entrySet = new ArrayList(category.entrySet());
Iterator it = entrySet.iterator();
while(it.hasNext()) {
System.out.println(it.next));
Which two code fragments, when inserted independently at line **, enable the code to compile?

  • A. Map<String, List<String>> category = new HashMap<List> ();
  • B. Map<String, List<String>> category = new HashMap<<>,List<>>();
  • C. Map<String, List<String>> category = new HashMap<> ();
  • D. Map<String, List<String>> category = new HashMap <String, ArrayList<String>> ();
  • E. Map<String, List<String>> category = new HashMap<String, List<String>> ();
  • F. Map<String, List<String>> category = new HashMap<String, List <>> ();


Answer : C,E

Explanation: E: Redundant type arguments in new expressions. Use diamond operator instead.

Page:    1 / 6   
Total 90 questions