4

This question was recently asked in an interview that i attended.

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

I was asked to preserve both method main signature (name, number and type of parameters, return type) and implementation (body of method),

and to make this program to output to standard console message "Magic Output !"

I took around 2 minutes to answer. My solution was to put a static block there and output the required string.

static{
   System.out.println("Magic Output !");
}

This does work but , it prints both Magic Output ! and Hello, World!

How can i make it to output only magic string ?

3 Answers 3

9
static{
   System.out.println("Magic Output !");
   System.exit(0);
}

or funnier (depends on String implementation - works with openjdk 8):

static {
  System.out.println("Magic Output!");
  try {
    Field f = String.class.getDeclaredField("value");
    f.setAccessible(true);
    f.set("Hello, World!", new char[0]);
    f.set(System.lineSeparator(), new char[0]);
  } catch (Exception ignore) { }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer in a short time! I want to up vote 10 times.
1

You could also use static nested classes to achieve that.

public class MagicOutput {   
    public static void main(final String argv[]) { 
        System.out.println("Hello, World!"); 
    }   
    static class System {
        static Out out = new Out();
    }
    static class Out {
        void println(String s){
            java.lang.System.out.println("Magic Output !");
        }
    }
}

Comments

0

Redirect System.out to an instance of PrintStream using System.setOut() on the static block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.