May 14, 2007

Do You Code Like This? - The Answer

If you recall my last post, I posed a question like so,

System.out.println(true?false:true==true?false:true);

Anyway, this is a small Java code. If you are ensure about the notation, it is a shorthand for "if...else" statement.

The ?: notation is explained as follows,

( [boolean-expression] ? [true-part] : [false-part] )

An example of the use of the "?:" notation is as follows,

int i = 5;
System.out.println((i < 10)? true: false);

The result should print out "true".

This notation certainly saves a bit of time but it tends to make code very difficult to read.

If we return to the question I posed, if we were to rewrite that statement, we would get the following:

if (true) {
false;
} else {
if (true == true) { false; } else { true; }
}

Was this flow-control what the developer wanted to execute? I apologize for putting the next if statement in a single line but it was to differentiate the nested-if statement.

So, what is the answer?

If you were smart, you would have taken this code and pasted it in a class, compiled and executed it. (^^)

The answer was.... "false". LOL!!!! Obvious, right?

Remember that you can not have a variable named after a Java reserved keyword, so, there was no way that "true" or "false" were variables. ;)

I do advocate the use of the "?:" notation, but only when it is very clear. I would not condone using the "?:" notation when there is a big chunk of code in between each true or false parts.

No comments:

Post a Comment

Please feel free to add your comments. However, take note that your comments may be edited or deleted as seen fit by the author of this blog.

Take note that the author of this blog may not be held responsible for the comments which may be insensitive, vulgar or controversial.

Related Posts with Thumbnails