如何使用 " 初始化字符串?"? [英] How can a string be initialized using " "?

查看:40
本文介绍了如何使用 " 初始化字符串?"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 String 和其他类一样是一个类,那么如何使用双引号对其进行初始化?

解决方案

Java 字符串很特殊

<块引用>

Java 的设计者决定在面向对象的语言中保留原始类型,而不是将一切都变成对象,以提高语言的性能.原语存储在调用堆栈中,需要更少的存储空间并且操作成本更低.另一方面,对象存储在程序堆中,需要复杂的内存管理和更多的存储空间.

<块引用>

出于性能原因,Java 的 String 被设计为介于原始类型和类之间.

例如

String s1 = "Hello";//字符串字面量字符串 s2 = 你好";//字符串字面量字符串 s3 = s1;//相同的引用String s4 = new String(你好");//字符串对象String s5 = new String(你好");//字符串对象

注意:字符串文字存储在一个公共池中.这有助于共享具有相同内容的字符串的存储空间以节省存储空间.通过new操作符分配的String对象存储在heap中,相同的内容不共享存储.

If String is a class just like any other, how can it be initialized using double quotes?

解决方案

Java String is Special

The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.

For performance reason, Java's String is designed to be in between a primitive and a class.

For example

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

Note: String literals are stored in a common pool. This facilitates the sharing of storage for strings with the same contents to conserve storage. String objects allocated via the new operator are stored in the heap, and there is no sharing of storage for the same contents.

这篇关于如何使用 &quot; 初始化字符串?&quot;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆