18

Is this :

String function() { return someString; }

Any different than this ?

String function() { return(someString); }

Its the return I'm interested in. I see the 2nd style less frequently, is it just convention or is the return in parenthesis actually doing something different?

aioobe
  • 413,195
  • 112
  • 811
  • 826
JHarnach
  • 3,944
  • 7
  • 43
  • 48
  • 3
    by convention, your method names should also be lower case... it helps disambiguate them from Classes/Interfaces/Enums, which are always upper camel cased. – whaley Nov 18 '10 at 15:56
  • 8
    Every time I see `return(foo);` (in any C-dialect language) I want to stab someone in the eye. `return` is not a function -- stop pretending that it is. –  Nov 18 '10 at 16:50
  • neither is while nor if though... correct me if I'm wrong, but isn't return the *only* control-flow keyword thats *not* followed by a left parenthesis? – aioobe Nov 18 '10 at 17:07
  • See also the similar C++ question http://stackoverflow.com/questions/7943052/return-a-vs-return-a – Raedwald Jan 14 '15 at 21:39

5 Answers5

29

No, there is no functional difference at all between wrapping the return value in parentheses or not.

According to the Java Coding Convention (section 7.3), you should stick with

return expression;

unless the paretheses makes it more clear:

7.3 return Statements
A return statement with a value should not use parentheses unless they make the return value more obvious in some way.

Example:
return;
return myDisk.size();
return insert(root, data);
return (size ? size : defaultSize);

Tui Popenoe
  • 2,098
  • 2
  • 23
  • 44
aioobe
  • 413,195
  • 112
  • 811
  • 826
6

The return with parentheses is not 'calling the return function with an argument', it is simply putting parentheses around the value of the return statement. In other words it is just like writing:

a = (b + c);

instead of

a = b + c;

It's perfectly legal but it doesn't add anything useful. And convention is that you don't write the parentheses.

DJClayworth
  • 26,349
  • 9
  • 53
  • 79
5

No difference, just convention

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
3

There was a fashion for formatting C return statements like function calls some decades ago. The obvious problem with that is that they aren't function calls.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

There is no functional difference but both a far from writing style in Java because: 1. there are not functions. Java has methods. 2. method names never capitalized. 3. we do not write method body in the same line with its name.

shortly this is the java style:

String method() {
    return someSting;
}
AlexR
  • 114,158
  • 16
  • 130
  • 208