Reputation: 422
This was an exam question which I couldn't complete.
How do you get the following java code to print false by only editing code within the MyClass constructor?
public class MyClass{ public MyClass(){ } public static void main(String[] args) { MyClass m = new MyClass(); System.out.println(m.equals(m)); } }
You are NOT allowed to override the equals method, or change any of the code within the main method. The code must run without the program crashing.
According to my research, you can't set a Java object reference to null when you instantiate a class. So I'm officially stumped.
Upvotes: 22
Views: 764
Reputation: 23614
That was tough!!
public MyClass() {
System.setOut(new PrintStream(new FilterOutputStream(System.out) {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if(new String(b).contains("true")) {
byte[] text = "false".getBytes();
super.write(text, 0, text.length);
}
else {
super.write(b, off, len);
}
}
}, true));
}
Or Paul Boddington's simplified version:
PrintStream p = System.out;
System.setOut(new PrintStream(p) {
@Override
public void println(boolean b) {
p.println(false);
}
});
Or AJ Neufeld's even more simple suggestion:
System.setOut(new PrintStream(System.out) {
@Override
public void println(boolean b) {
super.println(false);
}
});
Upvotes: 18
Reputation: 37645
Another solution is
public MyClass() {
new PrintStream(new ByteArrayOutputStream()).println(true);
try {
Field f = String.class.getDeclaredField("value");
f.setAccessible(true);
f.set("true", f.get("false"));
} catch (Exception e) {
}
}
The first line is needed because it is necessary for the string literal "true"
to be encountered in the PrintStream
class before the backing array is modified. See this question.
Upvotes: 4
Reputation: 3323
This is my solution
public class MyClass {
public MyClass() {
System.out.println("false");
// New class
class NewPrintStream extends PrintStream {
public NewPrintStream(OutputStream out) {
super(out);
}
@Override
public void println(boolean b) {
// Do nothing
}
}
NewPrintStream nps = new NewPrintStream(System.out);
System.setOut(nps);
}
public static void main(String[] args) {
MyClass m = new MyClass();
System.out.println(m.equals(m));
}
}
Basically, this is the variation of @fikes solution.
Upvotes: 1
Reputation: 129497
Something along these lines, I would guess:
public MyClass() {
System.out.println(false);
System.exit(0);
}
EDIT: I found a puzzle very similar to yours in Java Puzzlers, except in that question the only restriction was that you could not override equals, which basically makes the solution to overload it instead and simply return false
. Incidentally, my solution above was also given as an alternative answer to that puzzle.
Upvotes: 14