您可以用多种方式来创建字符串。每次创建字符串,Java虚拟机都会在背后创建一个String对象。下面有两种创建字符串对象的方式,并且将字符串对象赋值给一个变量:
String a = "abc";
String b = new String("abc"); // DON'T DO THIS
避免使用第二种方式[2]。第二种方式创建了两个String对象,这样降低了性能:首先,Java虚拟机创建了String对象“abc”。然后,java虚拟机创建一个新的String对象,并把字符串“abc”传入构造函数。同样重要的是,这是一次不必要的构造,使得您的代码阅读起来更加困难。
You can construct Strings in a number of ways. Any time you create a new String literal, the Java VM constructs a String object behind the scenes. Here are two ways to construct a String object and assign it to a reference variable:
String a = "abc";
String b = new String("abc"); // DON'T DO THIS
Avoid the second technique.[2] It creates two String objects, which can degrade performance: First, the VM creates the literal String object "abc". Second, the VM constructs a new String object, passing the literal "abc" to its constructor. Equally as important, it is an unnecessary construct that makes your code more difficult to read.
String a = "abc";
String b = new String("abc"); // DON'T DO THIS
避免使用第二种方式[2]。第二种方式创建了两个String对象,这样降低了性能:首先,Java虚拟机创建了String对象“abc”。然后,java虚拟机创建一个新的String对象,并把字符串“abc”传入构造函数。同样重要的是,这是一次不必要的构造,使得您的代码阅读起来更加困难。
You can construct Strings in a number of ways. Any time you create a new String literal, the Java VM constructs a String object behind the scenes. Here are two ways to construct a String object and assign it to a reference variable:
String a = "abc";
String b = new String("abc"); // DON'T DO THIS
Avoid the second technique.[2] It creates two String objects, which can degrade performance: First, the VM creates the literal String object "abc". Second, the VM constructs a new String object, passing the literal "abc" to its constructor. Equally as important, it is an unnecessary construct that makes your code more difficult to read.