java - 在 Java 中连接字符串

标签 java string operator-overloading string-concatenation

<分区>

Possible Duplicate:
Why does + work with Strings in Java?

以下语句在 Java 中有效。

int a=50;
String tmp="a = ";
String b=tmp+a;

b 类型的字符串现在包含 a = 50(作为字符串)。

尽管 tmp 是 String 类型,aint 类型,但还是进行了连接(即使 Java 不支持运算符重载)。

Java 不支持运算符重载的原因之一(与其他语言一样。事实上,我对任何语言都没有深入的了解)。

Java does not support operator overloading. Operator overloading is sometimes a source of ambiguity in C++ program, and the Java design team felt that it causes more trouble than benefit.

More关于它。

这个语句 String b=tmp+a; 是如何计算的?内部必须有一些等效的运算符重载概念。


只有一个问题:我们可以从字面上看到它是如何实现的,还是我们应该相信“这只是语言的一个特性”?

我听说 Java 编译器使用 StringBuilder/StringBuffer(使用 append() 方法)来实现这一点,但我不确定。

最佳答案

从技术上讲,这只是一个恰好具有相同符号的不同运算符。它是“字符串连接运算符”;见section 15.18.1 of the Java Language Specification .

关于实现,JLS 是这样说的:

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

关于java - 在 Java 中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11593759/

相关文章:

PHP 如何在条形图/图形中打印字符串中的字符数?

python - 如何在python中替换特定单词后的下一个单词

rust - 我们可以创建自定义 Rust 运算符吗?

java - 如何使 JFilechooser 允许用户仅从一个文件夹中进行选择?

java - 使用 XSSFSheetXMLHandler 获取样式信息

python - Python 中的字符串或列表替换

c++ - 不能使用 operator<< 作为方法?

c++ - 运算符重载 : ok MSVS but fails in g++

java - 访问仅资源 .jar 中的资源

java - 将文件从 Android 应用程序上传到 SFTP 服务器