Wednesday, July 15, 2009

Puzzle 42 - Equally Unequal.

Language - Java | Type - Concept | Last date 19-Jul-2009 12:00 p.m. IST | Points 3

This might be old puzzle, someone asked this question on Java Ranch. I think it's a pretty neat & tough puzzle why don't you folks give it a try!

class Equals {

public static void main(String args[]){

<sometype> x = <somevalue>;

System.out.println(x
== x) //This should print false

}

}


Replace the placeholders <sometype> and <somevalue> with any construct or value so that the System.out.println() prints out a false. No other changes/additions/deletions are permitted.

Looking for a hint? I think one might just show up on twitter soon.

Got an answer? Leave your answer here.

13 comments:

  1. Well, I missed the previous puzzle...

    This one is quite simple

    double x = 0.0/0.0;
    System.out.println(x == x);

    NaN is always different than NaN and 0.0/0.0 is not a number :)

    ReplyDelete
  2. double x = Double.NaN;
    or
    float x = Float.NaN;

    should do - here isNaN needs to be used instead to be able to determine if a floating point value is "not a number". Well of course the trick above would do also, in fact that's what the implementation of isNaN() is based on.

    ReplyDelete
  3. double x = Double.NaN

    ReplyDelete
  4. double x = Double.NaN;

    ReplyDelete
  5. According to JLS NaN is unordered and always make equality operator return false.

    public static void main(String[] args){
    // double x = Double.NaN
    float x = Float.NaN;
    System.out.println(x == x);
    }

    ReplyDelete
  6. Maybe not what you have in mind:
    Object x = new Object(){
    Object get(){
    System.out.println(false);
    System.exit(0);
    return this;
    }
    }.get();

    I will think about another solution if I have time...

    ReplyDelete
  7. This is not soo abuzz:
    Object x = new Object(){
    {
    System.out.println(false);
    System.exit(0);
    }
    };

    ReplyDelete
  8. are u kidding in both cases(Primitive and Object type )it printed true

    plz let me know my email id is nsureshreddy@live.com

    this is what i compiled and run

    class Equals {
    public static void main(String args[]){
    int x = 10;// String x="10"
    System.out.println(x == x); //This should print false
    }
    }

    ReplyDelete
  9. class Equals {
    2 public static void main(String args[]){
    3 float x = Float.Nan;
    4 System.out.println(x == x) //This should print false
    5 }
    6 }

    ReplyDelete
  10. class Equals {
    public static void main(String args[]){
    float x = Float.Nan;
    System.out.println(x == x) }
    }

    ReplyDelete

Solution for this question?