mercoledì 6 novembre 2013

Q36


Given the code fragment:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 

class Base {
     public void process() throws IOException {
          FileReader fr = new FileReader ("userguida.txt");
          BufferedReader br = new BufferedReader (fr);
          String record;
          while ((record = br.readLine())!=null){
                System.out.println(record);
          }
     }
}

public class Derived extends Base {
     public void process() throws Exception {
          super.process();
          System.out.println("process");
     }

     public static void main (String[] args){
          try {
                new Derived.process();
          } catch (Exception e) {
                System.out.println(e.getClass());
          }
     }
}

 
If the file userguide.txt does not exist, what is the result?

A.
An empty file is created and success is printed.


B.
class java.io.FileNotFoundException.


C.
class java.io.IOException.


D.
class java.lang.Exception.


E.
Compilation fails.



La risposta è E .

Ci si aspetta che le istanze della classe Base aderiscano al contratto dichiarato, quindi che process aderisca alla clausola trhows IOException . Sovrascrivendo process e cambiando l’eccezione con una più alta si ha la rottura del contratto e anche la violazione del principio di sostituzione di Liskov.

Multiple markers at this line
            - Exception Exception is not compatible with throws clause in Base.process()
            - overrides Base.process

Se invece il metodo che sovrascrive avesse utilizzato una eccezione più bassa del metodo padre il codice avrebbe compilato :

class Base {
     public void process() throws Exception  { ...
public void process() throws IOException { ...

In questo caso ovviamente si avrebbe avuto un errore all’invocazione del super : Unhandled exception type Exception
 

Q35

Given:

public class Counter {
     public static int getCount(String[] arr) {
          int count = 0;
          for (String var : arr) {
                if (var != null)
                     count++;
          }
          return count;
     }

     public static void main(String[] args) {
          String[] arr = new String[4];
          arr[1] = "C";
          arr[2] = "";
          arr[3] = "Java";
          assert (getCount(arr) < arr.length);
          System.out.print(getCount(arr));
     }
}

And the commands:

javac Counter.java
java ‘ea Counter

What is the result?

A.
2


B.
3


C.
NullPointException is thrown at runtime


D.
AssertionError is thrown at runtime


E.
Compilation fails



Risposta B
Il codice compila e quindi la E è falsa . Quando si eseguono i comandi si fa prima una compilazione con javac e poi un lancio con java. Il parametro ea serve ad attivare le asserzioni. Da eclipse si può fare la stessa cosa scrivendo –ea in Run ConfigurationsArgumentsParametri VM .
Se non si attivano le asserzioni queste saranno ignorate.
Il flusso del programma è :
1)    Si crea un array lungo 4
2)    Si inseriscono 3 elementi nelle posizioni 1,2 e 3 e si lascia l’elemento 0 a null.
3)    Il metodo getCount conta gli elementi non nulli dell’array, quindi 3.
4)    L’asserzione  verifica che questo conto (3) sia minore della lunghezza dell’array (4) . quindi l’asserzione è verificata e il flusso procede oltre.
5)    Alla fine si stampa il conto e quindi si ha la stampa del numero 3.
Per vedere cosa succede se l’asserzione non è verificata si può aggiungere un elementi non nullo in posizione 0 : arr[0] = "C"; , oppure cambiare l’asserzione : assert (getCount(arr) == arr.length); . In questo caso l’asserzione non viene verificata e si ottiene il messaggio di errore :

Exception in thread "main" java.lang.AssertionError
     at Counter.main(Counter.java:16)
 
 
Riferimenti:
 

Q34

Given the code fragment:

     String s = "Java 7, Java 6";
     Pattern p = Pattern.compile("Java.+\\d");
     Matcher m = p.matcher(s);
     while (m.find()) {
          System.out.println(m.group());
     }

What is the result?

A.
Java 7

B.
Java 6

C.
Java 7, Java 6

D.
Java 7
java 6

E.
Java

Risposta C

1) si definisce una stringa s = "Java 7, Java 6".

2)si definisce un Pattern p. Un pattern è una rappresentazione compilata di una espressione regolare.

Java. significa : ogni espressione che inizia con Java e a destra ha un qualunque carattere ( . ); nel nostro caso il carattere è uno spazio.

\\d Significa una cifra cioè un carattere in [0-9]

+ Indica una o più occorrenze.

Quindi Java.+\\d indica : trova tutte le sottostringhe che iniziano per Java, proseguono con un carattere qualsiasi e terminano con una qualunque cifra :
 

L’unica modalità richiesta dall’esame è quella greedy. L’espressione regolare sopra scritta può essere intesa in due modi :
 

Infatti .+ è greedy . Se avessimo voluto un quantificatore diverso, ad esempio reluctant avremmo dovuto usare:  .?+  .

Quindi l’unica corrispondenza che viene trovata è l’intera stringa.

3) Una volta creato il pattern, cioè il “comportamento” si può creare il matcher, cioè la “corrispondenza” tra l’ingresso e le regole dell’espressione regolare.

4)Il matcher a questo punto può essere scorso con il metodo find()che trova di volta in volta la corrispondenza successiva. In pratica quindi si stampano tutte le corrispondenze trovate.

Q33

Given:

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter {
     private AtomicInteger c = new AtomicInteger(0);
 
     public void increment() {
          // insert code here
     }
}


Which line of code, inserted inside the increment () method, will increment
the value of c?

A. c.addAndGet();

B. c++;

C. c = c+1;

D. c.getAndIncrement ();

 

Risposta  D

A
Questo codice non compila perché non viene passato l’obbligatorio parametro di ingresso :
The method addAndGet(int) in the type AtomicInteger is not applicable for the arguments ()
Dovrebbe essere c.addAndGet(1); .

B
L’operatore postifix (++)  si applica solo agli interi e quindi il codice non compila essendo c un AtomiInteger .
Type mismatch: cannot convert from AtomicInteger to int

C
L’operatore somma (+) non è applicabile al tipo AtomicInteger.
The operator + is undefined for the argument type(s) AtomicInteger, int

D
Questo è il modo corretto di incrementare un AtomicInteger di 1 .
Riferimenti :


 

martedì 5 novembre 2013

Q32

Given:

public class Runner {
     public static String name = "unknown";
     public void start() {
          System.out.println(name);
     }
     public static void main(String[] args) {
          name = "Daniel";
          start();
     }
}

What is the result?

A.
Daniel


B.
Unknown


C.
It may print”unknown”or”Daniel”depending on the JVM implementation.


D.
Compilation fails.


E.
An exception is thrown at runtime.



Risposta E :

Stiamo cercando di fare un riferimento statico ad un metodo non statico :

Cannot make a static reference to the non-static method start() from the type Runner

Q31

Given:
class Counter extends Thread {
     int i = 10;
     public synchronized void display (Counter obj) {
          try {
                Thread.sleep(5);
                obj.increment(this);
                System.out.println(i);
          }
          catch (InterruptedException ex) { } 
     }
     public synchronized void increment (Counter obj) {
          i++;
     }
}

 
public class Test {
     public static void main(String[] args) {
          final Counter obj1 = new Counter();
          final Counter obj2 = new Counter();
          new Thread(new Runnable() {
                public void run() {
                     obj1.display(obj2);
                }
          }).start();
          new Thread(new Runnable() {
                public void run() {
                     obj2.display(obj1);
                }
          }).start();
     }
}

 

From what threading problem does the program suffer?

A.
deadlock


B.
livelock


C.
starvation


D.
race condition




Risposta A

Si incontra un problema di deadlock perché i 3d si bloccano a vicenda.

Infatti il 3D1 parte  ma il piccolo sleep lo ferma abbastanza per permettere anche al 3D2 di partire. A questo punto il 3D1 sta lavorando e come obj ha obj2 mentre anche il 3D2 sta lavorando e come obj ha obj1. Quando si prova a fare il primo increment , stiamo chiamando il metodo increment con obj2 come ingresso, ma questo è il 3D2 che è occupato. Solo che 3D2 non si libera mai perché ad un certo punto prova anch’egli a fare un increment dell’obj1, che a sua volta è occupato.

Quindi 3D1 aspetta 3D2 che però aspetta 3D1 : Deadlock.
 

Q30

Given the code fragment:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
 

public class IsContentSame {
     public static boolean isContentSame() throws IOException {
          Path p1 = Paths.get("D:\\faculty\\report.txt");
          Path p2 = Paths.get("C:\\student\\report.txt");
          Files.copy(p1, p2, StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS);
          if (Files.isSameFile(p1, p2)) {
                return true;
          } else {
                return false;
          }
     }

     public static void main(String[] args) {
          try {
                boolean flag = isContentSame();
                if (flag)
                     System.out.println("Equal");
                else
                     System.out.println("Not equal");
          } catch (IOException e) {
                System.err.println("Caught IOException: " + e.getMessage());
          }
     }
}

What is the result when the result.txt file already exists in c:\student?

A.
The program replaces the file contents and the file’s attributes and prints Equal.


B.
The program replaces the file contents as well as the file attributes and prints Not equal.


C.
An unsupportedoperationException is thrown at runtime.


D.
The program replaces only the file attributes and prints Not equal.


Risposta  B

Infatti pur rimpiazzando il secondo file con il primo isSameFile  controlla se due path puntano allo stesso unico file e non se due file diversi sono uguali nel contenuto. Quindi il ritorno di IsContentSame è false.

Riferimenti:

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html