I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.
I know that:
if (var) { ... }
i
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.
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.