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

Q29

Given the following incorrect program:

import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {
     final int low;final int high;
     static final int THRESHOLD =  /*--*/ ;
     MyTask (int low,int hight) {
          this.low=low;this.high=hight;
     }

     Integer computeDirectly() {
          return null;
     } /*..*/

protected void compute() {
     if (high - low <= THRESHOLD)
          return computeDirectly();
     int mid = (low + high) / 2;
     invokeAll (new MyTask (low,mid), new MyTask(mid,high));
}
}

 

Which two changes make the program work correctly?

A.
Results must be retrieved from the newly created MyTask instances and combined.


B.
The threshold value must be increased so that the overhead of task creation does not dominate the cost of computation.


C.
The midpoint computation must be altered so that it splits the workload in an optimal manner.


D.
The compute () method must be changed to return an Integer result.


E.
The compute () method must be enhanced to (fork) newly created tasks.


F.
The myTask class must be modified to extend RecursiveAction instead of RecursiveTask


Risposta A e C

Riferimenti:

 

Q28

Q28

Q27

Given that myFile.txt contains:

First
Second
Third

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

public class ReadFile04 {
     public static void main(String[] args) {
          try (BufferedReader buffIn = new BufferedReader(new FileReader(
                     "D:\\faculty\\myfile.txt"))) {
                String line = "";
                int count = 1;
 

                buffIn.mark(1);
               

                line = buffIn.readLine();
                System.out.println(count + ": " + line);
               

                line = buffIn.readLine();
                count++;
                System.out.println(count + ": " + line);
                buffIn.reset();
               

                line = buffIn.readLine();
                count++;
                System.out.println(count + ": " + line);
 

          } catch (IOException e) {
                System.out.println("IOException");
          }
     }
}
What is the result?

A.
1: First
2: Second
3: Third

B.
1 : First
2: Second
3: First

C.
1: First
2: First
3: First

D.
IOExcepton

E.
Compilation fails

 

Risposta B

readLine() legge una riga di testo dallo stream di ingresso restituendo una stringa.
una riga finisce quando nello stream si incontrano le sequenze "\n",  "\r", oppure "\r\n" e queste sequenze non vengono restituite nella stringa.
Quindi ad ogni readline il programma legge la riga corrente e si posiziona alla riga successiva.
Invece mark consente di mettere un segnalino in un punto dello stream e con il comando reset di tornare al punto marcato.

Quindi il codice esegue queste operazioni:
1)    si marca lo stream in questo punto, cioè all'inizio.
2)    si legge e si stampa la prima riga. Readline ci posiziona alla riga successiva, quindi alla seconda.
3)    si legge e si stampa la riga corrente, quindi la seconda. Readline ci posiziona alla riga successiva, quindi alla terza.
4)    si fa il reset, quindi si ritorna alla marcatura e quindi alla prima riga.
5)    si legge e si stampa la riga corrente, quindi la prima. Readline ci posiziona alla riga successiva, quindi alla seconda ma intanto il programma è arrivato alla fine.
 

Q26

Given:

public class Print01 {
     public static void main(String[] args) {
          double price = 24.99;
          int quantity = 2;
          String color = "Blue";
          // insert code here. Line ***
     }
}
 
Which two statements, inserted independently at line ***, enable the program to produce the following output:


We have 002 Blue pants that cost $24.99.

A.
System.out.printf(“We have %03d %s pants that cost $%3.2f.\n”,quantity, color, price);

B.
System.out.printf(“We have$03d$s pants that cost $$3.2f.\n”,quantity, color, price);

C.
String out = String.format (“We have %03d %s pants that cost $%3.2f.\n”,quantity, color, price); System.out.println(out);

D.
String out = System.out.format(“We have %03d %s pants that cost $%3.2f.”,quantity, color, price);
System.out.println(out);

E.
System.out.format(“We have %s%spants that cost $%s.\n”,quantity, color, price); 

 

La risposta è A e C
 

A. E’ corretto.

B. No perchè $03d$s e $$3.2f.\n non sono formattate secondo la sintassi e quindi vengono stampate così come sono :
We have$03d$s pants that cost $$3.2f.

C.  E la stesso risultato di A ma usando format invece di printf

D.  No perchè si assegna ad una stringa un PrintStream infatti il codice non compila.
 

E.  E’ tentativo di usare una sintassi minimale ma è errato perché la sintassi %s stampa l'ingresso come una stringa quindi le parole risultano attaccate una all'altra e non viene "paddato" il numero 2 con gli zeri d'avanti.

We have 2Bluepants that cost $24.99.