Syntactical meaning of putting strings in parentheses

493 Views Asked by At

I like to confuse myself with syntactical things and not to concentrate on really doing stuff. :)

I know what I can do with this thing but I still want to know what is really happening under the hood.

So... I just wonder what are the reasons and situations where putting strings inside parentheses is meaningful. I saw a method that returned something like

return (string1 + " " + string2);
5

There are 5 best solutions below

1
On BEST ANSWER

The parenthesis have no effect in this example. The code you posted is equivalent to this:

return string1 + " " + string2;

Generally speaking there is no specific interaction between parenthesis and Strings or string literals. Parenthesis have the same semantics as in "normal" expressions: to group operations.

In some cases parenthesis might be necessary to specify the correct interpretation:

System.out.println("foo: " + 1 + 1);   // will print "foo: 11"
System.out.println("foo: " + (1 + 1)); // will print "foo: 2"
0
On

It is a legal construct and it has the same purpose as parenthesis in algebra, to ensure that the operation gets done before the return. In actuality in this case it is not needed and if you did

return string1 + " " + string2;  

The result would be the same. Maybe the author of the code thought it might be more readable ?

0
On

Just readability. If you want to emphasis on the returning object, you put the parentheses. But they are not necessary.

0
On

This makes return look like a function call, which it in fact is not. So, this is a example where you should not use parentheses.

0
On

I just wonder what are the reasons and situations where putting strings inside parentheses is meaningful.

Here's another example:

string1 + " " + string2.substring(a,b)

and:

(string1 + " " + string2).substring(a,b)

are two very different beasts.