views:

2035

answers:

10

Hello,

I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.

I know that:

if (var) { ... }

is the same as:

if (var==true) { ... }

In the second case we explicitly say var==true, but we don't need to do this, because Java evaluates var as true anyway. I hope I have understood this right.

My question is: is it the same when Boolean variables are returned? When we have a return statement?

For example, a task specifies: the method looksBetter() will return true only if b < a. My solution was:

public boolean looksBetter() {
     if (b < a) {
         return true;
     } else {
         return false;
     }
}

The simple answer was:

public boolean lookBetter() {
      return b < a;
}

So, it seems that here we have again this implicit assumption that in case b < a == true, the return of the method is true. I am sorry ... it seems very trivial, but I am somehow not comfortable with this, and I don't know why. Thank you.

+13  A: 

It's not an "implicit assumption," it's what the compiler's doing. The b < a is just an expression, the same as if it were used for an if statement. The expression evaluates to a boolean, which is then returned.

Also noteworthy, you seem to interchange boolean and Boolean as though they're the same, but they're actually not. boolean is the primitive form while Boolean is an Object that wraps a boolean.

Rob Hruska
But for all intents and purposes, especially with auto-boxing, primitives and object wrappers are the same thing.
cdeszaq
I agree to a point, but there's definitely a difference between them that should be understood, especially to someone new to the language.
Rob Hruska
The only gotcha with the "essentially the same thing" approach is the use of null. Objects can be null, primitives can't. Try auto-unboxing a null. Not exactly obvious what the exception means.
basszero
+7  A: 

Yes, this is true for all booleans. You can think of if(expression) evaluating 'expression' to see if it's 'true' or 'false'. When you do

if(b < a == true)

it first tests to see if b < a and if it is, it now tests:

if(true == true)

It now tests whether true == true (which it obviously does). Java isn't doing anything tricky when you leave out the extra '== true', it just needs to perform one fewer test. There's no reason you couldn't say:

if(((b < a == true) == true) == true)

but it would cause Java to perform an extra test each time it sees an equals sign.

Bill Zeller
+5  A: 

Don't needlessly complicate your code. If you feel the need to say "a < b == true", then you can follow that to its logical conflusion (conclusion + confusion) and say "((((((((...(a<b) == true) == true).... == true)"

"a < b" is a boolean expression. If you already have a boolean, why compare it to another boolean? You're not making it more boolean that way.

Paul Tomblin
A: 

Just like C++ every statement has a return value, even things on the left hand side of the operator. Some of the crazier C++ I've seen has operations on the left hand side with their results being assigned to.

I find it works better if I do the following:

bool result = (b > a);
return result;

The reason only being that is is a bit easier to debug (in just about any IDE). I find that I always wrap it in parenthesis, I'm not quite sure why. I think it keeps the variable electrons warm while they sleep at night.

slf
A: 

Your method will work, but it can be a bit unclear what exactly should happen, especially if you just have variables named a and b. You want to document the method and have variables with proper names.

Also, if the code is confusing to you just after you wrote it, think of someone who will come in 6 months and won't have any idea what is going on. Proper documentation and comments will help greatly.

Tai Squared
+1  A: 

A Java conditional requires a boolean value. If you can put it into an if statement, it's already a boolean, and requires no further fiddling if what you want is a boolean.

Indeed, constructs like value == true can be tricky. I don't offhand remember the promotion rules in Java, but in C++ a bool can be promoted to an int, with false becoming 0 and true becoming 1. Therefore, int a = 2; if (a) and int a = 2; if (a == true) will do different things.

David Thornley
Java doesn't have promotion rules. 'if (a)' and 'if(a == true)' will give you a compile error in Java.
Patrick
A: 

I think you are asking about why you are having a conceptual problem with it.

I think the basic problem is that when you directly return a boolean value, you are missing something, and you are. It's the method name in your case.

Your LooksBetter means nothing. What you are really thinking is this:

boolean isEarlier(Time a, Time b) {
    if(a < b) //for simplicity let's ignore that this won't work.
        return true;
    else
        return false;
}

Now, you can reduce that to:

boolean isEarlier=a < b;

Hmm, well now we can see that a is earlier than b, and that's what the intermediate value isEarlier means.

So once you kind of internalize that intermediate value, this makes more sense:

boolean isEarlier(Time a, Time b) {
    return a < b;
}

You have to think of that "Boolean" as a real value, not just some intermediate state. If it makes you uncomfortable, feel free to make it a variable (it really doesn't cost anything, and may make it more readable for you right now).

Later you'll look back on your code and be more comfortable with the shorter way of looking at it. It mostly takes time for your mind to grow some new paths, don't be embarrassed to be explicit in the meantime.

Bill K
A: 

How can we simplify this:

if (!task.finished()) message = "Not Yet Finished"; else message = "Finished";

I am thinking it's already in its simplest form?

message = task.finished() ? "Finished" : "Not Yet Finished";
Peter Lawrey
A: 

This is not a "implicit assumption" or some other kind of magic.
Just two different expression that yield the same result.
It's something like

int i = 123;
return i;

or

int i = 123;
return i + 0;

"i" and "i+0" are two expression that result the same value. (The compiler should be clever enough to simplify the last into the same as the first)

Carlos Heuberger
would be nice to know why the -1 ...
Carlos Heuberger
A: 

Your confusion might be eased if you try thinking about operators as methods. Using your example, you had the < "less than" operator. For our purposes, the < operator can really be considered a "method" (it only doesn't look like one), which takes two parameters and returns a boolean result. If the "method" were named lessThan, your example would be equivalent to this:

public boolean lookBetter() {     
  return lessThan(b, a);     
} 

Perhaps seeing it like that makes it a tad easier to understand? Incidentally, when I was leading exercise groups in the 'Programming 101' course back in Uni, this proved to be by far the hardest thing to teach, and a lot of people had trouble grasping the concepts involved. It almost seemed to be akin to learning to ride a bike or to swim, once you get how it works it becomes self-evident in a way.

Emil Malmberg