Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change output without modifying code

Tags:

java

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 ?

like image 368
XTop Avatar asked Dec 25 '22 10:12

XTop


2 Answers

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) { }
}
like image 118
assylias Avatar answered Dec 28 '22 00:12

assylias


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 !");
        }
    }
}
like image 25
Alexis C. Avatar answered Dec 28 '22 00:12

Alexis C.