lunedì 16 settembre 2013

Q7

Which two are valid initialization statements?

 A.
Map<String, String> m = newSortedMap<String, String>();

B.
Collection m = new TreeMap<Object, Object>();

C.
HashMap<Object, Object> m = newSortedMap<Object, Object>();

D.
SortedMap<Object, Object> m = new TreeMap<Object, Object> ();

E.
Hashtablem= new HashMap();

F.
Map<List, ArrayList> m = new Hashtable<List, ArrayList>();

Risposta D e F

A.
SortedMap è un'interfaccia che estende proprio l'interfaccia Map. Infatti :
public interface SortedMap<K, V> extends Map<K, V>
Quindi questo codice non ha senso perchè si sta cercando di instanziare un' interfaccia.


B.
TreeMap viene da Map infatti :
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V> à
public abstract class AbstractMap<K,V> extends Object implements Map

Non possiamo instanziare un oggetto TreeMap e assegnare il reference ad una variabile di tipo Collection.
Dobbiamo fare un cast per arrivare almeno a compilare:
Collection m = (Collection) new TreeMap<Object, Object>();

Invece avrebbe avuto senso partire dall'interfaccia Map, infatti questo codice compila:
Map m = new TreeMap<Object, Object>();

C.
public interface SortedMap<K, V> extends Map
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,

SortedMap è una interfaccia e noi stiamo cercando di instanziarla. Questo non è possibile.

D.
Questo è corretto perchè stiamo instanziando un oggetto di tipo TreeMap (public class TreeMap<K,V> extends AbstractMap<K,V>) assegnando il reference ad una variabile di tipo SortedMap (public interface SortedMap<K, V> extends Map).


E.
Questo codice non ha senso perchè Hashtablem non può essere risolto in una variabile non essendo mai stato creato.


F.
Questo è corretto perchè stiamo instanziando un oggetto di tipo Hashtable (public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>,) assegnando il reference ad una variabile di tipo Map (public interface Map<K,V>).

Riferimenti :
http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html

Q6


Which four are syntactically correct?
 

A.
package abc;
package def;
import java.util . * ;
public class Test { }

B.
package abc;
import java.util.*;
import java.util.regex.* ;
public class Test { }

C.
package abc;
public class Test {}
import Java.util.* ;

D.
import java.util.*;
package abc;
public class Test {}

E.
package abc;
import java.util.*;
public class Test{}
F.
public class Test{}
package abc;
importjava.util.*{}

G.
import java.util.*;
public class Test{}
 
H.
package abc;
public class test

La risposta è BEGH
A.
E' errata perchè la classe è dichiarata appartenere a due package

B.
E' corretta

C.
E' errata perchè l'ordine è sbagliato. L'import precede sempre la dichiarazione della classe
D.
E' errata perchè l'ordine è sbagliato. il package precede sempre gli import

E.
E' corretta

F.
E' errata perché la classe deve seguire sempre package e import.
G.
La classe Test è correttamente inserita nel package di default, che non va quindi dichiarato.
H.
E' corretta.

Q5

Given the code fragment:

public class Test {
       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 ***, enable you to print files with the extensions.java,
.htm, and .jar.

A.
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,”*.{java, htm,jar}”)){

B.
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,”*. [java, htm, jar]“)) {

C.
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,”*.{java*, htm*, jar*}”)) {

D.
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir,”**.{java, htm, jar}”)) {

La risposta è A e D.
Infatti sia A che D indicano di prendere tutti i file che terminano in java oppure htm oppure jar.

La B non funziona perchè oltre allo spazio tra l'asterisco e le parentesi (probabilmente un errore nella domanda) le parentesi sono quadre. Le parentesi quadre indicano una collezione di caratteri.
[java, htm, jar] significa : Prendi tutti i file che contengano almeno una j oppure a oppure  v oppure  a oppure uno spazio oppure h ecc fino alla r di jar.

La C invece prende tutti anche i file la cui estensione inizia con il termina specificato. Ad esempio .java ma anche .javadoc , a causa dell'asterisco finale.

Riferimenti
http://docs.oracle.com/javase/tutorial/essential/io/dirs.html
  Listing a Directory's Contents
  Filtering a Directory Listing By Using Globbing

http://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob

Argomento glob
Files.newDirectoryStream accetta un argomento glob. La sintassi glob serve a specificare un comportamento dei percorsi.

Nei nostri casi:
Un asterisco * significa tutto, dal lato dell'asterisco.
Due asterischi ** significa tutto, dal lato degli asterischi ma penetra anche dentro le sottocartelle.
Ad esempio :
*.html prende tutti i file che finiscono in .html

Le parentesi graffe indicano una collezione, e quindi una sorta di OR.
Ad esempio :
◦{sun,moon,stars} significa : sun oppure moon oppure star.

Le parentesi quadre indicano una collezione di singoli caratteri:
[aeiou] significa : prendi tutti file che abbiamo almeno una vocale minuscola.

venerdì 13 settembre 2013

Q4

Given:
import java.io.File;
import java.nio.file.Path;
 
public class Test12 {
       static String displayDetails(String path, int location) {
             Path p = new File(path).toPath();
             String name = p.getName(location).toString();
             return name;
       }
 
       public static void main(String[] args) {
             String path = "project//doc//index.html";
             String result = displayDetails(path, 2);
             System.out.print(result);
       }
}
What is the result?
A.
doc


B.
index.html


C.
an IllegalArgumentException is thrown at runtime.


D.
An InvalidPthException is thrown at runtime.


E.
Compilation fails.


Risposta B.
Si crea un File con ingresso "project//doc//index.html". Poi dal File si estrae il path. Infine si stampa il 3° elemento del percorso :
p.getName(0).toString()) à project
p.getName(1).toString()) à doc
p.getName(2).toString()) à index.html

Q3

Given the code fragment:

public void otherMethod() {
       printFile("");      }
public void printFile(String file) {
       try (FileInputStream fis = new FileInputStream(file)) {
             System.out.println(fis.read());
       } catch (IOException e) {
             printStackTrace();
       }
}

Why is there no output when otherMethod is called?

A.
An exception other than IOException is thrown.

B.
Standard error is not mapped to the console.

C.
There is a compilation error.

D.
The exception is suppressed.

Risposta B.
Infatti quando il programma a run time cerca di aprire lo stream file, essendo vuoto, restituisce una java.io.FileNotFoundException:  (No such file or directory). Il metodo printStackTrace() fa qualcosa che non si sa. Se si tratta, come è probabile di un errore e il vero codice fosse:
  catch (IOException e) {
                    e.printStackTrace();
             }
Anche in questo caso la risposta è B perché la FileNotFoundException non viene catturato dalla gestione della IOException.
Riferimenti:

Q2

Given the code fragment:

public void ReadFile (String source) {
       char[] c = new char [128];
       int cLen = c.length;
       try (FileReader fr = new FileReader (source)) {
       int count = 0;
       int read = 0;
       while ((read = fr.read(c)) != -1) {
       count += read;
       }
       System.out.println("Read: " + count + " characters.");
       } catch (IOException i) {
       }

What change should you make to this code to read and write strings instead of character arrays?

A.
Change FileReader to Readers.

B.
Change FileReader to DataReader.

C.
Change FileReader to File.

D.
Change FileReader to BufferReader.




Risposta : D
A.
Readers non esiste.
Se invece ci si riferiva a java.io.Reader si tratta di una classe astratta che non può essere instanziata.
B.
DataReader non esiste.
D.
La risposta è giusta perchè BufferReader implementa la classe astratta Reader che legge stream di caratteri.
Codice per testare :
importjava.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
BufferedReader fr = new BufferedReader(new FileReader(source))

Riferimenti:
http://docs.oracle.com/javase/6/docs/api/java/io/Reader.html

 

Q1

Given the code fragment:

       public static void main(String[] args) {

             String source ="d:\\company\\info.txt";

             String dest ="d:\\company\\emp\\info.txt";

             // insert code fragment here. Line ***

             } catch (IOException e) {

             System.err.println("Caught IOException"+ e.getMessage());

             }

         }

Which two try statements, when inserted at line ***, enable the code to successfully move the file info.txt to the destination directory, even if a file by the same name already exists in the destination directory?

A.
try (FileChannel in = new FileInputStream (source). getChannel(); FileChannel out = new FileOutputStream(dest).getChannel()) { in.transferTo(0, in.size(), out);

B.
try (Files.copy(Paths.get(source),Paths.get(dest));
Files.delete (Paths.get(source));

C.
try (Files.copy(Paths.get(source), Paths.get(dest),StandardCopyOption.REPLACE_Existing); Files.delete(Paths.get(source));

D.
try (Files.move(Paths.get(source),Paths.get(dest));

E.

try(BufferedReader br = Files.newBufferedReader(Paths.get(source), Charset.forName("UTF- 8"));

BufferedWriter bw = Files.newBufferedWriter(Paths.get(dest), Charset.forName("UTF-8")); String record = "";

while ((record = br.readLine()) ! = null) {

bw.write(record);

bw.newLine();

}

Files.delete(Paths.get(source));

La risposta è C e E

A.
Anche se transferTo scrive sopra il file se è già esistente non cancella il file di partenza.
Quindi non realizza uno spostamento ma una copia.

B.
Il metodo copy senza opzioni non sovrascrive i file già esistenti e da luogo ad una java.nio.file.FileAlreadyExistsException.

C
Funziona bene perché con l’opzione il metodo copy sovrascrive il file di destinazione.

D
Il metodo move senza opzioni non sovrascrive i file già esistenti e da luogo ad una java.nio.file.FileAlreadyExistsException.

E
Funziona perché newBufferedWriter se il file esiste già lo tronca ad una dimensione pari a 0 prima di iniziare a scriverlo.

 
Riferimenti: