将字符串放在括号中的语法意义

发布于 2024-10-16 19:20:41 字数 195 浏览 6 评论 0原文

我喜欢让自己与语法上的事情混淆,而不是专注于真正做的事情。 :)

我知道我能用这个东西做什么,但我仍然想知道幕后到底发生了什么。

所以...我只是想知道将字符串放在括号内有意义的原因和情况是什么。我看到一个返回类似内容的方法

return (string1 + " " + string2);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

物价感观 2024-10-23 19:20:41

括号在此示例中不起作用。您发布的代码与此等效:

return string1 + " " + string2;

一般来说,括号和 String 或字符串文字之间没有特定的交互。括号与“正常”表达式具有相同的语义:对操作进行分组。

在某些情况下,可能需要括号来指定正确的解释:

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

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"
零時差 2024-10-23 19:20:41

它是一个合法的构造,与代数中的括号具有相同的目的,以确保操作在返回之前完成。实际上,在这种情况下,不需要它,如果您这样做,

return string1 + " " + string2;  

结果将是相同的。也许代码的作者认为它可能更具可读性?

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 ?

倒带 2024-10-23 19:20:41

只是可读性。如果你想强调返回的对象,你可以加上括号。但它们不是必要的。

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

眼泪淡了忧伤 2024-10-23 19:20:41

这使得 return 看起来像一个函数调用,但实际上不是。因此,这是一个不应使用括号的示例。

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.

命硬 2024-10-23 19:20:41

我只是想知道是什么原因
放置字符串的情况
括号内是有意义的。

这是另一个例子:

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

和:

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

是两种截然不同的野兽。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文