Java Quiz #46 : flagada stream

Maintenant que la rage et la fureur de Devoxx sont retombées, je vous propose de résoudre un petit quiz facile sur Java 8 !

A votre avis, qu'affiche le code suivant ?

Attention, ne trichez pas : interdiction d'exécuter le code avant d'avoir trouvé ! Mais pouvez consulter la documentation de la classe IntStream.

public class Quiz {
    public static void main(String[] args) {
 
        IntStream.rangeClosed(1, 10)
                 .map(i -> i++)
                 .forEach(System.out::println);
 
    }
}
Lire la suite...

Java Quiz in Unicorn land

Some days ago, ZeroTurnaround, of JRebel fame, published a funny Java Quiz on their website.
It is not very hard, and there are at least 3 different solutions that I know of.

Below is my solution ; but try to find your own before taking a look !

Lire la suite...

Java Quiz #45

Français :
Le pattern Singleton est bien connu ; son but est de garantir qu'une classe donnée ne possède qu'une seule instance.
Mais comment le protéger contre une réinstanciation par réflexion ?

Note: le but n'est pas de réimplémenter le Singleton sous la forme d'un enum, mais de protéger son implémentation classique, proposée ci-dessous.

English :
Singleton is a well-known design pattern ; its purpose is to guarantee that only one instance exists in the VM for that particular class.
But how can we protect the class from being instanciated again via reflection ?

(below : a basic Singleton implementation)


public class Singleton {
 
    private static final Singleton INSTANCE = new Singleton();
 
    public static Singleton getInstance() {
        return INSTANCE;
    }
 
    private Singleton() {
    }
 
    public void sayHello() {
        System.out.println("Hello World !");
    }
 
}
Lire la suite...

Java Quiz #44

FR:
Le but de ce quiz est de rendre ce code plus performant d'un ordre de magnitude uniquement en ajoutant 1 ligne. Evidemment, le benchmark doit toujours réaliser la même fonction, c'est-à-dire mesurer le temps nécessaire pour transformer le tableau d'entiers en tableau de wrappers d'entiers.
Mes résultats : avant : 1700ms (très variable), après : 65ms (très stable)
La réponse sera apportée dans une semaine !

EN:
The goal of this quiz is to make this code run an order of magnitude faster, simply by adding a single line. Please note that the benchmark must still measure the time nessary to copy an int array into an Integer array.
Results on my box : before : 1700ms with high variability, after : 65ms, very stable.
The answer will be given in a week.

public class Quiz44 {
 
    private static final int NB_VALUES = 10000000;
    private static final int MAX_VALUE = 1000;
    private static final int NB_RUNS = 10;   
 
    public static void main(String[] args) {
 
        Integer[] boxedValues = new Integer[NB_VALUES];
        int[] values = initValues();
 
        System.out.println("Benchmarking...");
        for (int run = 1; run <= NB_RUNS; run++) {
            long t1 = System.currentTimeMillis();
            for (int i = 0; i < NB_VALUES; i++) {
                boxedValues[i] = values[i];
            }
            long t2 = System.currentTimeMillis();
            System.out.printf("Run %2d : %4dms%n", run, t2 - t1);
        }
    }
 
    /** Nothing important here, just values init. */
    private static int[] initValues() {
        System.out.println("Generating values...");
        int[] values = new int[NB_VALUES];
        Random random = new Random();
        for (int i = 0; i < values.length; i++) {
            values[i] = random.nextInt(MAX_VALUE);
        }
 
        return values;
    }
 
}
Lire la suite...

Java Quiz #43

FR :
Cela faisait longtemps que je n'avais pas publié de quiz ! L'inspiration vient à manquer, le temps aussi... Mais en voici un tout neuf, présenté en exclusivité lors de ma conférene au YAJUG, le JUG du Luxembourg.
Pouvez-vous repérer le problème de ce code (bien entendu, sans le compiler ni le coller dans votre éditeur préféré) ?

EN :
This quiz has been presented in exclusive to the YAJUG, the java User Group of Luxembourg.
Can you spot what is wrong with this code without compiling it or pasting it in your favorite IDE ?

public class DataSetCreator {
 
    public static void main(String[] args) throws IOException {
        new DataSetCreator().createDataSet(20, new FileOutputStream("test.dat"));
    }
 
    public void createDataSet(int dataSetSize, OutputStream os) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(os);
        Random rand = new Random(System.currentTimeMillis());
        for (int i = 0; i < dataSetSize; i++) {
            oos.writeObject(new Data(rand.nextInt(100)));
        }
        oos.close();
    }
 
    private class Data implements Serializable {
        int number;
        private Data(int number) {
            this.number = number;
        }
        public int getNumber() {
            return number;
        }
    }
 
}
Lire la suite...

Java Quiz #42 : A string too far

(FR)
Ce code semble totalement inoffensif, mais peut causer des erreurs sous certaines circonstances.
Pouvez-vous détecter le problème ?

(EN)
This code may seem harmless, but will cause serious problems in certain circumstances.
Can you spot the problem ?

  1. public class Quiz42 {
  2.  
  3. public static void main(String[] args) {
  4. new Quiz42();
  5. }
  6.  
  7. private static final int MAX_STRING_LENGTH = 6;
  8. private Map<Integer, String> db = new HashMap<Integer, String>();
  9. private int nextId = 0;
  10.  
  11. public Quiz42() {
  12. // Introductory text
  13. Console console = System.console();
  14. if (console==null) {
  15. System.out.println("Don't cheat in Eclipse :)");
  16. System.exit(0);
  17. }
  18. console.printf(
  19. "FakeDB 1.0%n"+
  20. "'exit': exits FakeDB.%n" +
  21. "'db' : dumps the DB content.%n"+
  22. "Words are limited to %d characters.%n%n> ",MAX_STRING_LENGTH);
  23.  
  24. // Read - Eval loop
  25. String s = null;
  26. while ((s = console.readLine()) != null) {
  27. if ("exit".equals(s)) {
  28. break;
  29. }
  30. if ("db".equals(s)) {
  31. console.printf("DB content : %s%n",db);
  32. continue;
  33. }
  34.  
  35. // Check DB constraints client-side, then save the user's string.
  36. if (s.length() > MAX_STRING_LENGTH) {
  37. console.printf("String too long, please enter another one.%n");
  38. continue;
  39. }
  40. persistInDatabase(s.toUpperCase());
  41. console.printf("Saved '%s'.%n> ",s);
  42. }
  43. }
  44.  
  45. private void persistInDatabase(String s) {
  46. // Simulate a database constraint
  47. if (s.length() > MAX_STRING_LENGTH) {
  48. throw new IllegalArgumentException("DATA TOO LARGE");
  49. }
  50. db.put(nextId++, s);
  51. }
  52.  
  53. }
Lire la suite...

Java Quiz #41 : time attack !

(FR)
La cellule d'expertise de votre entreprise a développé un Timer pour que vous puissiez mesurer les performances de votre application, mais... ils ont juste oublié de fournir une méthode pour récupérer la valeur du compteur ! Comment faire pour l'afficher une fois la mesure prise ?
Vous ne pouvez intervenir que sur la classe Quiz41, et il est interdit de modifier le code existant ou d'utiliser la Réflexion.
Bonne chance !

(EN)
The Architects Team developed a Timer class to help you measure the performance of your code, but... they forgot to provide a method to get the timer's value ! How can you get it back and print it in the console ?
You can only alter the Quiz41 class ; modifying the already existing code or using Reflection is forbidden.
Good luck !

  1. public class Quiz41 {
  2.  
  3. public static void main(String[] args) throws InterruptedException {
  4.  
  5. Timer timer = new Timer();
  6. timer.start();
  7. Thread.sleep(new Random().nextInt(2000));
  8. timer.stop();
  9.  
  10. }
  11. }
  1. public class Timer {
  2.  
  3. private TimerThread thread = new TimerThread();
  4.  
  5. public void start() {
  6. thread.start();
  7. }
  8.  
  9. public void stop() {
  10. thread.stop();
  11. }
  12.  
  13. public static class TimerThread extends Thread {
  14. private AtomicInteger counter = new AtomicInteger(0);
  15.  
  16. @Override
  17. public void run() {
  18. try {
  19. while (!isInterrupted()) {
  20. counter.incrementAndGet();
  21. Thread.sleep(100);
  22. }
  23. } catch (InterruptedException e) {
  24. interrupt();
  25. }
  26. }
  27.  
  28. public int getCounter() {
  29. return counter.get();
  30. }
  31. }
  32. }
Lire la suite...

Java Quiz #40

To please your Project Manager, a former developer (yeaaars ago), you sometimes let him help you develop some "very important" parts of your application.

Today, he's in charge of displaying "Hello World" by iterating on a list containing those words. Alas, distracted by his going on vacation this very afternoon, he forgets to add "World" to the list before starting the iteration. Trying to correct his mistake, he adds it a few lines later, but now his code unexpectedly breaks down at runtime ("this must be a JVM bug !").

A few minutes before leaving, he asks you to find a solution in his absence, with the following instructions :

  • Do not modify his existing code, it's Perfect (of course).
  • The FIXME tag shows where you're allowed to insert your corrective code
  • He must be able to understand your solution when he comes back (so

using Reflection is not an option).

Are you worth the trust of your beloved Manager ?

  1. final List<String> list = new ArrayList<String>() {{ add("Hello"); }};
  2. final Iterator<String> iterator = list.iterator();
  3. System.out.println(iterator.next());
  4. list.add("World");
  5. // FIXME : work here while I'm sunbathing
  6. System.out.println(iterator.next());

Hints - Keep in mind that :

  • the iterator is declared final
  • this is only a code fragment, so you cannot use System.exit(0) or return; you wouldn't like your application to terminate prematurely, would you ?
  • since you cannot modify the existing code, you cannot delete or ignore the last line, which must print "World"

Note : I must thank Romain Revol for helping me to write this quiz. Romain successfully attended the "Heinz Kabutz's Java Specialist Master Course" training session I presented in France in June at Zenika's office.

Lire la suite...

Java Quiz #39

If you're not getting your athletic body's tanned on a beach this week, here is a small quiz to keep your brain fit.
What does this code snippet do ?

  1. public class Quiz39 {
  2.  
  3. public static void main(String[] args) {
  4. int[] array = null;
  5. try {
  6. array[0] = array[(array = createArray())[array.length - 1]];
  7. } finally {
  8. System.out.println("Array = " + Arrays.toString(array));
  9. }
  10. }
  11.  
  12. public static int[] createArray() {
  13. return new int[]{1, 2, 3, 4};
  14. }
  15.  
  16. }
Lire la suite...

Java Quiz #38

Can you help the poor Exception to escape the Matrix ?
Beware, the Agents are nearby and will spot you if you attempt in any way to modify or remove the existing lines of code ! (but you may add new ones).

  1. public class Matrix {
  2. public static void getTheSpoon() {
  3. throw new java.lang.NoSuchMethodException("There is no spoon !");
  4. }
  5. }
  1. public class Test {
  2. public static void main(String[] args) {
  3. try {
  4. Matrix.getTheSpoon();
  5. } catch (Exception ex) {
  6. System.out.println(ex instanceof java.lang.NoSuchMethodException ? "You passed the Quiz !" : "You failed !");
  7. }
  8. }
  9. }
Lire la suite...

- page 1 de 6