gpt4 book ai didi

java - String类以及Java对其的依赖

转载 作者:行者123 更新时间:2023-12-02 18:25:14 24 4
gpt4 key购买 nike

所以大家都知道,你能写的最短的Java程序是:

public class Program{
public static void main(String []args){

}
}

人们会怀疑这个最短的程序仅由语言关键字、选定的名称(如类名/函数名/参数名)和一些语法(括号等)组成。

但是当你仔细观察时,突然会弹出 String 类。那么这是否意味着 Java 语言不能没有 String 类呢?或者甚至没有完整的标准库? (我认为 C++ 可以在没有标准库的情况下存在,不是吗?)

此外,我一直在查看 String 类代码,但没有找到运算符 + 和 += 的实现(也许其他可用?)。那么这是如何运作的呢?这是作为特殊情况嵌入编译器中的吗?这甚至可以将 String 类与 java 语言更紧密地绑定(bind)在一起?

是否还有其他类如此深入地嵌入 Java 语言中?

最佳答案

Java String 包含不可变的 Unicode 字符序列。 与 C/C++ 不同,其中字符串只是 char数组,Java String 是 java.lang 类的对象。

String is special class in Java and all String literal e.g. "abc"(anything inside double quotes) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space.

Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.

与普通类(class)不同:

   String is associated with string literal in the form of double-quoted
texts such as "Hello, world!".

You can assign a string literal directly into a String variable,
instead of calling the constructor to create a String instance.

The '+' operator is overloaded to concatenate two String operands.
'+' does not work on any other objects such as your Person.java etc.

String is immutable. That is, its content cannot be modified once it
is created. For example, the method toUpperCase() constructs and
returns a new String instead of modifying its existing content.

字符串在 Java 中受到特殊对待,因为它们在程序中经常使用。因此,效率(在计算和存储方面)至关重要。

Java的设计者决定在面向对象的语言中保留原始类型,而不是把一切都变成对象,以提高语言的性能。

原语存储在调用堆栈中,这需要更少的存储空间并且操作起来更便宜。另一方面,对象存储在程序堆中,需要复杂的内存管理和更多的存储空间。

The '+' operator, which performs addition on primitives (such as int and double), is overloaded to operate on String objects. '+' performs concatenation for two String operands. Java does not support operator overloading for software engineering consideration unlike C++ where you you can turn a '+' operator to perform a subtraction.

“+”运算符是唯一一个内部重载以支持 Java 中字符串连接的运算符。请注意,“+”不适用于任意两个对象。

JDK 编译器实际上使用 String 和 StringBuffer 通过“+”运算符来处理字符串连接。例如,

String msg = "a" + "b" + "c";

将被编译成以下代码以提高效率:

String msg = new StringBuffer().append("a").append("b").append("c").toString();

出于性能原因,Java 的 String 被设计为介于基元和类之间。

关于java - String类以及Java对其的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26185434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com