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 ?
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) { }
}
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 !");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With