Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Return writing style in Java

Tags:

java

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?

like image 433
JHarnach Avatar asked Nov 18 '10 15:11

JHarnach


People also ask

What is the return type of () method?

Every method in Java is declared with a return type and it is mandatory for all java methods. A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing). The type of data returned by a method must be compatible with the return type specified by the method.

Why do we write return in Java?

The return keyword finished the execution of a method, and can be used to return a value from a method.

Can a Java function return different types?

With generic Java collections, we can return multiple values of a common type. The collections framework has a wide spectrum of classes and interfaces.


2 Answers

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);

like image 69
aioobe Avatar answered Oct 11 '22 21:10

aioobe


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.

like image 29
DJClayworth Avatar answered Oct 11 '22 19:10

DJClayworth