mercoledì 30 ottobre 2013

Q25

Le collezioni in Java non erano in origine tipizzate. Per ovviare a questo problema di robustezza del codice dal Java 5 sono state introdotte le versioni generiche delle collezioni . Per mantenere la retro compatibilità del codice è però sempre possibile in java utilizzare le collezioni non generiche. Dal lato pratico ci sono due API, una per le collezioni generiche e una per quelle non generiche.

 
Sintassi per le collezioni non generiche :

          List  myList = new ArrayList();
          myList.add("stringa");
          myList.add(2);
          String s1 = (String) myList.get(0);
          int s2 = (int) myList.get(0);

La lista  myList non è generica.

Quindi ci possiamo mettere oggetti di tipi diversi (non type-safe), come una String o un int. Quando si recuperano gli oggetti siccome il compilatore non sa di che tipo sono gli oggetti così recuperati vanno castati.

L’ultima riga evidenzia il problema della collezioni non generiche; infatti il compilatore permette di scrivere la linea di codice ma questa a run time provoca una eccezione, infatti stiamo cercando di castare ad intero un elemento che in realtà è una stringa:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

      

Sintassi per le collezioni generiche :
          List<String>  myList = new ArrayList();
          myList.add("stringa");
     *    myList.add(2);
          String s1 = myList.get(0);
*    int s2 = (int) myList.get(0);
 

In questo caso il compilatore segnala subito un errore se proviamo ad inserire un elemento intero dentro la collezione generica. Ancora più importante il compilatore segnala un errore se si cerca di recuperare un intero da una collezione di Stringhe. Questo rende il codice più robusto.

 
 

martedì 29 ottobre 2013

Q24

Given the code fragment:

public class Base {
     BufferedReader br;
     String record;
     public void process() throws FileNotFoundException {
          br = new BufferedReader(new FileReader("manual.txt"));
     }
}

public class Derived extends Base {
     // insert code here. Line ***
     public static void main(String[] args) {
          try {
                new Derived().process();
          } catch (Exception e) {
          }
     }
}

Which code fragment inserted at line ***, enables the code to compile?
A.
       public void process() throws FileNotFoundException, IOException {
             super.process();
             while ((record = br.readLine()) != null) {
                    System.out.println(record);
              }
       }

B.
       public void process() throws IOException {
             super.process();
             while ((record = br.readLine()) != null) {
                    System.out.println(record);
              }
       }

C.
       public void process() throws Exception {
             super.process();
             while ((record = br.readLine()) != null) {
                    System.out.println(record);
              }
       }

D.
       public void process() {
             try {
                    super.process();
                    while ((record = br.readLine()) != null) {
                           System.out.println(record);
                    }
             } catch (IOException | FileNotFoundException e) {
             }
       }

E.
       public void process() {
             try {
                    super.process();
                    while ((record = br.readLine()) != null) {
                           System.out.println(record);
                    }
             } catch (IOException e) {
             }
       }

 

Risposta E

A.
Non compila perché l’eccezione non è compatibile con la classe padre:
Exception IOException is not compatible with throws clause in Base.process()

 
B.
Non compila perché l’eccezione non è compatibile con la classe padre:
Exception IOException is not compatible with throws clause in Base.process()

 
C.
Non compila perché l’eccezione non è compatibile con la classe padre:
Exception Exception is not compatible with throws clause in Base.process()

 
D.
Non compila perché l’eccezione FileNotFoundException estende IOException e quindi non è permesso catturarle entrambe in un blocco multicatch.

The exception FileNotFoundException is already caught by the alternative IOException

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: