Change output without modifying code
java
Solution
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) { }
}
Problem
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 ?