Skip to Content

Intro

I hate majority of Java quizzes. They are just boring.

 

First category of  them forces you to track tricky assignments between several variables spread  among crazy switch/case and for instructions. If you know how to  find the answer then it’s fine. If not – not so bad, majority of code you are  working with is more readable. But if you create something like this in your  own code, your team mates will kill you.

 

Second ones are dumb API questions. What interfaces are used in RMI?  What interface is necessary to implement to make servlet thread-safe? Rrrrh…

However, there are some questions that are funny but may crack your brains.  The ones that developers themselves use to quiz each other. Here is a small  collection of my favorite questions that I heard from colleagues and saw in  forums.

I have a small conversation with Craig regarding points for correct answers.  Actually, I had suggested 10, 20, 30 points for every question correspondingly.  Craig doubled amount of points, probably because October is a month of Java on  SDN 🙂

You may either mail me your answers to my alternate e-mail address  (see my business card) or post it here as comments. First way is preferred,  while more then one user may win  – take on account time zones, someone probably sleep when you are reading this. SDN is a global thing.

 

Question 1: Magic Output (20 points)

Let us start with the simplest question. Actually, this is not even  advanced Java – only intermediate skills are necessary.

 

Consider the following Java class:


package com.sap.sdn.jquiz;

public class MagicOutput {
    public static void main(final String argv[]) {
        System.out.println("Hello, World!");
    }
}

 
While preserving both method main signature (name, number and type  of parameters, return type) and implementation (body of method), make this program  to output to standard console message “Hello, SDN!”  Again, you may not alter a single character within the method main!!!  The resulted class must be executable with JRE 1.4; you may not use  classes besides public API of JDK 1.4

Question 2: As short as possible but not shorter (40 points)

I found this one quite long time ago. Actually, if you are programming animation  or some multithreading applications, or console application that accepts input  from screen, then sooner or later you may notice the behavior, necessary to  answer this question. It’s hardly a hint, just my own observation 🙂

You have the following Java class:


package com.sap.sdn.jquiz;

public class Minimalizmo {
  //START
  //END
}

 
Between START and END comments, add the shortest (in number of characters)  possible method with return type other then void. Resulted class must be  syntactically correct, i.e. it must compiles successfully on JDK1.4;  you may not use classes besides public API of JDK 1.4.

 

Just a notice to those who want to game the rules: if you are using classes  outside java.lang package, you must use fully qualified names, i.e. no import  statements please.

Question 3: Green Java (60 points)

This is my favorite one, and, frankly it’s old as Java. Or as the first  Java IDE with syntax highlighting.  It’s simply a colorized fun! 🙂

You are probably noticed, that popular Java IDE-s like Eclipse-based  (Eclipse  itself and NetWeaver IDE for example), NetBeans and IntelliJ IDEA tend to display  commented out code in green. Ok, IDEA starting from version 5.0 prefers to use  grey by default. Anyway, the question is: write a classical program that  outputs “Hello, SDN World!” on console but its source is shown by IDE totally in green.  Every line and every character is green. Or grey 😉 Like commented out code.

Just a notice to those who want to game the rules: tweaking IDE settings  is not a solution.

To report this post you need to login first.

12 Comments

You must be Logged on to comment or reply to a post.

  1. Pran Bhas
    static{
         System.out.println(“Hello, SDN!”);
         System.exit(0);
    }

    public static void main(final String argv[]) {
         System.out.println(“Hello, World!”);
    };

    (0) 
    1. Valery Silaev Post author
      Pran,

      This is absolutely correct answer!

      There are 2 other guys who submit exactly the same answer:
      — Rich Heilman (he was the first, but considering locations you both live I’d say you are both winners)
      — Guru Subramanian (at 09:15 GMT today, I don’t know whether it was before your post or after)

      There is also one solution from Maksim Rashchynski that is different from yours. Moreover, I didn’t even expect it will work till I try! I will publish it a bit later.

      Actually, I know yet another solution. It also involves static block, but no call to System.exit.

      So let us decide the following — first question is closed. Probably, we accept yet another answer, if it will not contain call to System.exit.

      Now, try to solve second and third questions? Believe me, second question is quite simple (a bit surprising, though 😉

      Good luck!

      VS

      (0) 
      1. YiNing Mao
        import java.io.*;
        class Quiz
        {
             private static void setOutput(){
                  try{
                       System.setOut(new PrintStream(new File(“c:\\tmp.txt”)));
                  }
                  catch (Exception e){
                  }
             }     

             static{
                  System.out.println(“Hello, SDN!”);
                  Quiz.setOutput();
             }

             public static void main(final String argv[]) {
                  System.out.println(“Hello, World!”);
             };
        }

        (0) 
        1. Valery Silaev Post author
          YiNing,

          Exactly!

          But with in-memory output stream:
          static {
             System.out.println(“Hellow, SDN!”);
             System.setOut(
               new java.io.PrintStream(
                 new java.io.ByteArrayOutputStream()
               )
             );
          }

          I.e. output redirect is the third solution.
          So question 1 is closed.

          VS

          (0) 
  2. Valery Silaev Post author
    I get one solution to second question from Maksim Rashchynski.

    However, I do not accept it. He is using inner static classes. Well, nice cheat 😉

    package com.sap.sdn.jquiz;
    class Minimalizmo {
      //START
      I i(){return i;}
      //END

      static class I {}
      static I i = new I();
    }

    I do not say explicitly that you may not use inner classes. But I said that you must use qualified class names.

    So even Maksim get 16 characters, according to restrictions this should be (“com.sap.sdn.jquiz.Minimalizmo”.length() + 1) * 2 + 16.

    Just to get you one additional hint: the method is 17 characters long (including signature and implementation with all mandatory spaces and optional spaces stripped out). And, by the way, if inner classes will be allowed here, then it would be possible to optimize Maksims solution up to 15 characters 😉

    Anyone?

    VS

    (0) 
    1. Maksim Rashchynski
      public class Minimalizmo {
           //START
      int i(){throw i;}
           //END
      static RuntimeException i = new RuntimeException();
      }

      and

      public class Minimalizmo {
           //START
      I i(){throw i;}
           //END
           static class I {
           }
           
           static RuntimeException i = new RuntimeException();
      }

      So, 15 and 17 ;-).

      (0) 
      1. Valery Silaev Post author
        Max,

        You prove one thing — I cannot state question in a way that assumes only one exact solution. Or this is just a richness of Java syntax 🙂

        Ok, I write down a notice that you has the problem almost solved. Now, with all my apologizes, 2 clarifications:

        1. This must be just a method. No additional declarations inside class (static/instance fields, inner classes)
        2. Method may not be a constructor: my former manager reminded me that someone may treat constructor as method that return instance of class – no way.

        Now, let us revisit what you have been suggested:
        1. The shortest visibility modifier is so called “package private”, i.e. no modifier at all in source code.
        2. int as a name of return type is quite short. Frankly, I don’t know shorter one (among classes of java.lang package + primitives)
        3. Method that declares a return type may not return at all. For example, it may throw exception. By the way, this is quite common if you are implementing some really big interface when certain methods these are not used by program – just throw UnsupportedOperationException.

        All of these are right steps towards the answer. You need just one single step.

        VS

        P.S. Not bad – half of the quiz is solved less then in two days!

        (0) 
  3. Igor Nys
    Valery,

    Looks like as “your former manager” I have no choice, but to answer the last question in your quiz 🙂

    /* *\u002f

    public class Class1
    {
         public static void main(final String argv[])
         {
              System.out.println(“Hello, SDN World!”);
         }
    }

    Basically using a Unicode presentation to represent one of the comment symbols should tricks out the majority of Java IDE’s.

    (0) 
    1. Valery Silaev Post author
      As usual: manager comes – fun ends 🙂

      Ok, this is a correct answer. If anyone of SDN-ers understand the nature of trick, then please provide a solution that uses single-line comments (insetad of multiline). This will also be considered as correct answer with corresponding reward.

      VS

      (0) 
  4. Valery Silaev Post author
    Here is (correct) answer to questin 1 by Maksim:
    package com.sap.sdn.jquiz;

    public class MagicOutput {
      public static void main(final String argv[]) {
        System.out.println(“Hello, World!”);
      }
      static {
        System.out.println(“Hello, SDN!”);
        System.out.close();
      }
    }

    Surprisingly, closing console output works without errors! Studding JDK sources you may find out that further writes to console produce an error (as expected), but stream implementation catches these errors and do not propagate them further as exceptions.

    So we have questions [1] and [3] answered.
    Anyone for [2]? If someone didn’t notice hint in previous comment: even method is declared to return a value it’s possible to omit return statement, say, via unconditionally throwing an exception. Or other way 🙂

    VS

    (0) 
  5. Sergei Haller
    Hi Valery,

    not sure how I came to read this blog, but I also like the type of questions (well, probably not the Q1, as I had no chance solving it 🙂

    would that be a valid solution for Q2?

    public abstract class Minimalizmo {
      //START
      int f(){for(;;);}
      //END
    }

    this is approximately 17 chars long.

    cheers,
    Sergei

    (0) 

Leave a Reply