0

I am reading an existing Java code base right now and I have encountered a strange usage of the return statement. For example, there is a method isTrue() that is defined this way:

public boolean isTrue()
{
    return(true);  //Why? Notice: There is no whitespace between return and (true)
}

In all of the code I've encountered until this point, I've seen

public boolean isTrue()
{
    return true;  //What I normally see
}

This is pure speculation, but I assume these are the same. So, why would you ever do this? Furthermore is this a particular usage unique to java, or can this type of return be done in other languages? I know this is a fairly trivial question, but things like this will bother me until I know the answer. Thanks!

heez
  • 2,029
  • 3
  • 27
  • 39
  • `(x)` is a _primary expression_ whose value is the value of the enclosed expression, `x`. In other words, `(true)` equals `true`. Why does Java allow you to write `return (true)`? Because, given that we need parentheses in other places, it would only make the language more complicated to forbid them at top-level. Why would somebody _want_ to write it that way? Only the person who wrote it knows for sure. – Solomon Slow Jan 13 '15 at 20:44
  • Right. My main concern was primarily with the absence of a white space between `return` and the left parenth `(`. – heez Jan 14 '15 at 18:44
  • @heez Java is a "whitespace insensitive" language. This is the same reason why `x+y` and `x + y` are equivalent, as is `o.m(p)` and `o . m ( p )` - but don't write it like that! I recommend *including* the space [and omitting the parenthesis for simple expressions] or it makes `return` look like a method call or special operator - which it is not. – user2864740 Jan 14 '15 at 18:49
  • @user2864740 That's what I have been looking for! Thank you. Very interesting, I didn't know you could separate it to `o . m ( p )` like that--good to know. I agree, `return(true)` is definitely misleading and looks ridiculous. – heez Jan 14 '15 at 18:53

0 Answers0