Java Interview Puzzler
June 18th, 2009 by hashbrownThis is a puzzler we created at my work to use as an interview problem. I had a fun time taking it myself, and got it wrong the first time! It was designed to mimic some bad legacy code you might encounter when working on a large aging system, that has passed through many hands. Terrible coding practices, no javadocs or comments, etc. You are tasked to figure out what the heck it does.
First – does it compile? If not, how do you fix it?
Second – If it compiles, what is the output?
I’ll answer questions and post the solution in the comments.
01.
package
crazy;
02.
03.
public
class
Timing
extends
R {
04.
public
static
final
Integer t =
new
Integer(
"4"
);
05.
06.
07.
public
static
void
main(String[] args) {
08.
Timing t =
new
Timing(
11
);
09.
10.
System.out.print(t.foo);
11.
bat(t);
12.
}
13.
14.
void
fob() { fod(); }
15.
16.
public
Timing(
int
value) {
17.
18.
super
();
19.
foo = foo % value;
20.
bar();
21.
}
22.
23.
static
{
24.
System.out.print(
"6"
);
25.
26.
}
27.
28.
private
void
bar() {
29.
new
Baz().bar(
5
);
30.
tr =
"2"
;
31.
}
32.
33.
private
int
foo =
25
;
34.
35.
36.
static
void
r() { System.out.println(
"1"
); }
37.
}
38.
39.
abstract
class
R {
40.
41.
String tr =
"9"
;
42.
43.
static
void
bat(R r) {
44.
r.fob();
45.
System.out.print(r.tr);
46.
47.
}
48.
49.
private
int
negate(
int
bam) {
50.
return
bam * -
1
;
51.
}
52.
53.
54.
public
R() {
55.
System.out.print(
"7"
);
56.
}
57.
58.
void
fod() { System.out.print((
int
)Math.floor(.
99
)); }
59.
60.
61.
protected
final
int
t() {
62.
return
5
;
63.
}
64.
65.
class
Baz {
66.
67.
void
bar(
int
fob) {
68.
if
(fob ==
9
)
69.
System.out.print(String.valueOf(fob++));
70.
71.
System.out.print(String.valueOf(negate(fob++)));
72.
if
(fob ==
5
)
73.
System.out.print(String.valueOf(fob+=
2
));
74.
75.
}
76.
}
77.
78.
static
{
79.
System.out.print(
"8"
);
80.
}
81.
82.
abstract
void
fob();
83.
84.
}
Posted in geek stuff, programming | Comments Off on Java Interview Puzzler