Wednesday, April 15, 2009

Puzzle 16 – The ‘=’ puzzle

Language – Java/C++ | Type – Problem (Code) | Last date 19-Apr-2009 12:00 p.m. IST | Points 5

I was attending a session the other day and the instructor was adamant that the Java language is pretty cool (which it is – I just love it). To illustrate his point he referred to the fact that we cannot use a ‘=’ sign in a ‘if condition’ causing problems like it did in C/C++.

"Of course you can use a single = to in a 'if condition'. I have seen that happen so many times" I blurred out. "No way" he challenged. Care to take up this challenge for me?

Got an answer? Why don’t you leave it here.

7 comments:

  1. I suppose you refer to this:

    boolean b;
    if (b = true) {
    // compilation warning, but no error
    }

    The only thing that Java doesn't do is automatically consider non-null values as boolean values. Assignment expressions do not receive special treatment.

    ReplyDelete
  2. int i = 0;
    if ((i = 1) == 0) {
    System.out.println("This should not happen!");
    } else {
    System.out.println("It worked!");
    }

    ReplyDelete
  3. boolean t = true;
    boolean f = false;
    if (t = f) {
    // just a warning
    }
    if (!(t = f)) {
    // not even a warning
    }

    ReplyDelete
  4. boolean foo = true;
    if (foo = false) {
    // unreachable
    }

    ReplyDelete
  5. Scenario 1, it fails

    public class SimpleTest1 {
    public static void main(String[] args) {
    int i = 10;
    if (i = 9) {
    System.out.println("i not equal to 10");
    }
    }
    }

    Scenario 2, it works fine

    public class SimpleTest2 {
    public static void main(String[] args) {
    boolean possible = false;
    if (possible = true) {
    System.out.println("possible is true");
    }
    }
    }

    In scenario 1, it fails with the following error

    SimpleTest1.java:6: incompatible types
    found : int
    required: boolean
    if (i = 9) {
    ^
    1 error

    This is because, if statement always excepts the expression should result in boolean value.

    ReplyDelete
  6. A common example is

    BufferedReader br = ...
    String line;
    while((line = br.readLine()) != null) {
    // do something with the line
    }

    ReplyDelete
  7. Another odd use of = is in combination with assert.

    // debug is true is assertions have been turned on.
    boolean debug = false;
    assert debug = true;

    ReplyDelete

Solution for this question?