PDA

View Full Version : A puzzle for the Java gurus...


iapetus
06-24-2004, 12:31 PM
Here's a Java class with one line, which declares a local variable called x, replaced with a comment.

public class Test {
public static void main(String[] args) {
// Missing line of code declaring local variable x...
System.out.println("Test starting...");
if (x != x) {
System.out.println("Unpossible!");
}
System.out.println("Test finished.");
}
}

Compiling and running the class gives the following output:

Test starting...
Unpossible!
Test finished.

What is the missing line?

If you can't work out the answer immediately, a secondary question: what can you say about the data type of x?

maharg
06-24-2004, 12:59 PM
Does Java have a floating point type with a NaN value? :P

[edit] after looking it up, it does and it does:

public class Test {
public static void main(String[] args) {
float x = Float.NaN;
System.out.println("Test starting...");
if (x != x) {
System.out.println("Unpossible!");
}
System.out.println("Test finished.");
}
}

iapetus
06-24-2004, 01:03 PM
Got it in one. :) float x = Float.NaN; does the trick.

So much for the reflexivity of the == operator (and by extension, most equals() methods for classes storing floating point values). ;)

RevenantKioku
06-24-2004, 01:03 PM
float x = Float.NaN;
Although I wasn't the one who realized the right java code, someone next to me knew that.

Diablos
06-24-2004, 01:05 PM
Java sucks.

maharg
06-24-2004, 01:06 PM
Java sucks.

I hope you don't mean because of this, because then every language with an IEEE conforming floating point type sucks :)

iapetus
06-24-2004, 01:08 PM
No, Java is his favourite band...

Diablos
06-24-2004, 01:11 PM
No, Java is his favourite band...

har har har.