String Initialization in Java – Java中的字符串初始化

最后修改: 2019年 5月 16日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

Java String is one of the most important classes and we’ve already covered a lot of its aspects in our String-related series of tutorials.

Java字符串是最重要的类之一,我们已经在字符串相关的系列教程中介绍了其很多方面。

In this tutorial, we’ll focus on String initialization in Java.

在本教程中,我们将重点讨论Java中的String初始化。

2. Creation

2.创造

First of all, we should remember how Strings are created in Java.

首先,我们应该记住Strings在Java中是如何创建的。

We can use the new keyword or the literal syntax:

我们可以使用new关键字或字面语法。

String usingNew = new String("baeldung");
String usingLiteral = "baeldung";

And, it’s also important that we understand how Strings are managed in a specialized pool.

而且,我们还必须了解Strings是如何在一个专门的池中进行管理的

3. String Declaration Only

3.字符串仅声明

First, let’s just declare a String, without assigning a value explicitly.

首先,让我们只是声明一个String,而不明确赋值。

We can either do this locally or as a member variable:

我们可以在本地进行,也可以作为一个成员变量。

public class StringInitialization {

    String fieldString;

    void printDeclaredOnlyString() {
        String localVarString;
        
        // System.out.println(localVarString); -> compilation error
        System.out.println(fieldString);
    }
}

As we can see, if we try to use localVarString before giving it a value, we’ll get a compilation error. On the other hand, the console will show “null” for fieldString‘s value.

正如我们所见,如果我们试图在给它一个值之前使用localVarString,我们会得到一个编译错误。另一方面,控制台将显示fieldString的值为”null”

See, member variables are initialized with a default value when the class is constructed, null in String‘s case. But, we have to initialize local variables ourselves.

看,成员变量在构建类时被初始化为一个默认值,在String的情况下,null。但是,我们必须自己初始化局部变量。

If we give localVarString a value of null, we’ll see that the two are, indeed, now equal:

如果我们给localVarString一个null的值,我们会看到,现在两者确实是相等的。

String localVarString = null;
assertEquals(fieldString, localVarString);

4. String Initialization Using Literals

4.字符串使用字面的初始化

Let’s now create two Strings using the same literal:

现在让我们使用相同的字面意思创建两个Strings。

String literalOne = "Baeldung";
String literalTwo = "Baeldung";

We’ll confirm that only one object is created by comparing the references:

我们将通过比较引用来确认只有一个对象被创建。

assertTrue(literalOne == literalTwo);

The reason for this harks back to the fact that Strings are stored in a poolliteralOne adds the String “baeldung” to the pool, and literalTwo reuses it.

其原因可以追溯到Strings被存储在一个池中literalOneString“baeldung “添加到池中,literalTwo重新使用它。

5. String Initialization Using new

5.使用new进行String初始化

We’ll see some different behavior, though, if we use the new keyword.

不过,如果我们使用new关键字,我们会看到一些不同的行为。

String newStringOne = new String("Baeldung");
String newStringTwo = new String("Baeldung");

Although the value of both Strings will be the same as earlier, we’ll have to different objects this time:

虽然这两个Strings的值将与之前的相同,但这次我们将不得不使用不同的对象。

assertFalse(newStringOne == newStringTwo);

6. Empty Strings

6.空的字符串s

Let’s now create three empty Strings:

现在让我们创建三个空的Strings。

String emptyLiteral = "";
String emptyNewString = new String("");
String emptyNewStringTwo = new String();

As we know by now, the emptyLiteral will be added to the String pool, while the other two go directly onto the heap.

正如我们现在所知,emptyLiteral将被添加到String池中,而其他两个则直接进入堆。

Although these won’t be the same objects, all of them will have the same value:

尽管这些不会是相同的对象,但所有这些对象都会有相同的值

assertFalse(emptyLiteral == emptyNewString)
assertFalse(emptyLiteral == emptyNewStringTwo)
assertFalse(emptyNewString == emptyNewStringTwo)
assertEquals(emptyLiteral, emptyNewString);
assertEquals(emptyNewString, emptyNewStringTwo);

7. null Values

7、

Finally, let’s see how null Strings behave.

最后,让我们看看null Strings是如何表现的。

Let’s declare and initialize a null String:

让我们声明并初始化一个空的String

String nullValue = null;

If we printed nullValue, we’d see the word “null”, as we previously saw. And, if we tried to invoke any methods on nullValue, we’d get a NullPointerException, as expected.

如果我们打印nullValue,我们会看到 “null “这个词,正如我们之前看到的那样。而且,如果我们试图对nullValue调用任何方法,我们会得到一个NullPointerException,,正如预期的那样。

But, why does “null” is being printed? What is null actually?

但是,为什么 “null “会被打印出来?实际上,什么是null

Well, the JVM specification says that null is the default value for all references, so it’s not specifically tied to the String. And actually, the specification doesn’t mandate any concrete value encoding for null.

那么,JVM 规范说,null是所有引用的默认值,所以它并没有特别与String挂钩。而且实际上,该规范并没有为null规定任何具体的值编码。

So, where is “null” coming from for printing a String then?

那么,”null “是从哪里来的,用于打印String then?

If we take a look at the PrintStream#println implementation, we’ll see it calls String#valueOf:

如果我们看一下PrintStream#println实现,我们会看到它调用String#valueOf

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

And, if we look at String#valueOf, we get our answer:

而且,如果我们看一下String#valueOf,我们会得到答案:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

And, obviously, that’s the reason for “null”.

而且,很明显,这就是 “空 “的原因。

8. Conclusion

8.结语

In this article, we explored String initialization. We explained the difference between declaration and initialization. We also touched on using new and using the literal syntax.

在这篇文章中,我们探讨了String初始化。我们解释了声明和初始化之间的区别。我们还谈到了使用new和使用字面语法。

Finally, we took a look at what it means to assign a null value to a String, how the null value is represented in memory, and how it looks when we print it.

最后,我们看了一下将null值赋给String是什么意思,null值在内存中是如何表示的,以及我们打印它时的样子。

All code samples used in the article are available over on Github.

文章中使用的所有代码样本都可以在Github上找到over