martedì 29 ottobre 2013

Q23

An application is waiting for notification of changes to a tmp directory using the following code statements:

Path dir = Paths.get("tmp")
WatchKey key = dir.register (watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY) ;


In the tmp directory, the user renames the file testA to testB,


Which statement is true?

 

A.
The events received and the order of events are consistent across all platforms.

B.
The events received and the order of events are consistent across all Microsoft Windows versions.
 
C.
The events received and the order of events are consistent across all UNIX platforms.

D.
The events received and the order of events are platform dependent.

 
Risposta: A

Infatti se il file system ha un meccanismo di controllo per i cambiamenti nei file le API se ne avvantaggiano, altrimenti vanno in polling aspettando gli eventi.

Riferimento:
http://docs.oracle.com/javase/tutorial/essential/io/notification.html

Q22

Given:
             StringBuffer b = new StringBuffer("3");
            System.out.print(5+4+b+2+1);
 
What is the result?
 
A.
54321
 
B.
9321
 
C.
5433
 
D.
933
 
E.
Output is Similar to: 9java.lang.StringBuffer@100490121.
 
F.
Compilation fails.
                  
La risposta è F perchè The operator + is undefined for the argument type(s) int, StringBuffer .
Si potrebbe far compilare il codice in questo modo :
System.out.print(5+4+b.toString()+2+1);   

lunedì 28 ottobre 2013

Q21


Which four are true about enums?

A.   An enum is typesafe.

B.   An enum cannot have public methods or fields.

C.   An enum can declare a private constructor. OK

D.   All enums implicitly implement Comparable.

E.   An enumcan subclass another enum.

F.   An enum can implement an interface.

Riposta:

ACDF

A.  Un enum è type safe.

B.  Un enum può avere campi e metodi pubblici.

C.  Un enum può dichiarare un costruttore privato.

D.  Un tipo enum è Comparable.

E.  Un enum non può subclass un altro enum perché questo violerebbe il principio di Liskov visto che si va ad aggiungere altri valori enum.

F.  Un enum può implementare interfacce.

 

Riferimenti :


martedì 22 ottobre 2013

Q20


Given:

abstract class Boat {
      public static void main(String[] args) {
      }
}

class Sailboat extends Boat {
  public static void main(String[] args) {
    Boat b = new Sailboat(); // Line A
    Boat b2 = new Boat(); // Line B
  }
  String doFloat() { return "slow float"; } // Line C
  void doDock() { } // Line D
}

Which two are true about the lines labeled A through D?

A.
The code compiles and runs as is.


B.
If only line A is removed, the code will compile and run.

 
C.
If only line B is removed, the code will compile and run.

 
D.
If only line D is removed, the code will compile and run.


E.
Line C is optional to allow the code to compile and run.

F.
Line C is mandatory to allow the code to compile and run.

La risposta è CE

Il codice non compila a causa della linea di codice B :

Boat b2 = new Boat(); // Line B

Infatti si sta cercando di instanziare una classe astratta ma an abstract class can never be instantiated per definizione.

Quindi A è sbagliato e anche B e D perché l’errore è dato dalla linea B che in questi due casi rimane; invece la C è giusta perché rimuovendo la linea B si ottiene la compilazione del codice.

La linea C non è affatto obbligatoria per far compilare il codice, e quindi è giusta la E mentre è sbagliata la F.


Riferimenti :

http://docs.oracle.com/javase/tutorial/information/glossary.html

Q19

Given the code fragment:

             try {
                  String query = "SELECT * FROM Employee WHERE ID=110";
                  Statement stmt = conn.createStatement();
                  ResultSet rs = stmt.executeQuery(query);
                  System.out.println("Employee ID: " + rs.getInt("ID"));
            } 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.

La domanda non è molto chiara. Sono mancanti numeri di linea e quindi non si capisce a cosa si riferiscono le risposte C e D.

Comunque sia il codice così come è scritto non compila perché l’oggetto conn non è mai stato definito :
Statement stmt = conn.createStatement();  à conn cannot be resolved

Quindi la risposta è probabilmente C se conn viene usato alla linea 13 .


Se invece era prevista la definizione e l’istanziamento  della connessione il codice compila bene. In questo caso a run time il flusso si interrompe al momento di usare il ResultSet, infatti questo oggetto va scorso con un ciclo (while, next) e non può essere usato in questo modo. Definiamo una connessione (in questo caso pratico per Postgres) e scriviamo un codice che compila:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Principale {
      public static void main(String[] args)
      {
            try {
            Connection conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/test","test", "test");
            String query = "SELECT * FROM Employee WHERE ID=110";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            System.out.println("Employee ID: " + rs.getInt("ID"));
            } catch (Exception se) {
                  System.out.println("Error");
                  }
      }}
In questo caso si ha un errore che viene catturato dal catch. L’errore è :
Il «ResultSet» non è correttamente posizionato; forse è necessario invocare «next()».
Perciò la risposta sarebbe A : si stampa Error.

Per ottener un codice che possa funzionare si deve scorrere il ResultSet in maniera corretta, ad esempio :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Principale {
      public static void main(String[] args) throws SQLException {
            Connection conn = DriverManager.getConnection(
                        "jdbc:postgresql://localhost:5432/test", "test", "test");
            String query = "SELECT * FROM Employee WHERE ID=110";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                  System.out.println("Employee ID: " + rs.getInt("ID"));
            }
      }
}

Riferimenti:

 

lunedì 21 ottobre 2013

Q18

Given the directory structure that contains three directories: company, Salesdat, and Finance:

- Company
            - Salesdat
                        - Target.dat
            - Finance
                        - Salary.dat
                        - Annual.dat


And the code fragment :

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class SearchApp extends SimpleFileVisitor<Path> {
       private final PathMatcher matcher;

       SearchApp() {
             matcher = FileSystems.getDefault().getPathMatcher("glob:*dat*");
       }

       void find(Path file) {
             Path name = file.getFileName();
             if (name != null && matcher.matches(name)) {
                    System.out.println(name);
             }
       }

       public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
             find(file);
             return FileVisitResult.CONTINUE;
       }

       public static void main (String [] args) throws IOException
                 
             SearchApp obj = new SearchApp();       
             Files.walkFileTree(Paths.get("//Company"), obj);
       }
}


If Company is the current directory, what is the result?



A.
Prints only Annual.dat



B.
Prints only Salesdat, Annual.dat
 

C.
Prints only Annual.dat, Salary.dat, Target.dat

D.
Prints at least Salesdat, Annual.dat, Salary.dat, Target.dat

Risposta C.

Per scorrere i file contenuti dentro una alberatura di directory si può utilizzare l’interfaccia FileVisitor.

Un modo più semplice è quello di estendere la classe SimpleFileVisitor che estende l’interfaccia e sovrascrivere poi i soli metodi che interessano.

In questo esempio viene sovrascritto il solo metodo visitFile che viene invocato nel momento in cui siamo sopra il file ispezionato.

L’applicazione dell’esempio crea un cammino, un walk, tramite walkFileTree . Nel modo scritto il cammino ha solo il punto di inizio e il fileVisitor, quindi significa che andrà a cercare in tutti i sottolivelli senza alcun limite.




Quindi entreremo in per ogni file visitFile al livello pari o inferiore al punto di inizio. Quindi andremo a visitare ogni file.

Per ogni file faremo il match, per vedere se rispetta la condizioni di ricerca che abbiamo espresso con la sintassi glob.

glob:*dat* significa che troveremo

·         Tutti i file con estensione .dat.
·         Tutti i file che contengono dat in qualunque punto del nome.

Quindi troveremo :

Annual.dat
Salary.dat
Target.dat

Ma troveremmo anche questi file:
datprova.txt
provadatprova.txt
dat
provadat
datprova
provadatprova


Invece non troveremo mai nessuna directory perché non andremo mai ad esaminarle.

Riferimenti: