Re: Interesting Java interview question



Jack wrote:
Joshua Cranmer a écrit :

Why does the following compile, and what does the output look like?

System.out.println(new Object(){{{}}}.toString());

I would say that the output depends on some unprovided code. For example, if the following file were used:

public class InterviewQuestion {
public static void main(String... args) {
System.out.println(new Object(){{{}}}.toString());
}
}

it should print out `InterviewQuestion$1@<hex value>` where hex value will be the hash code of said object.


Why not "Object@<hex value>" ?


Because you're actually defining a new class with the new Object() {} syntax (look up anonymous inner classes).

--
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
.