In Java, Why String is non-primitive data type?

后端 未结 10 2078
闹比i
闹比i 2021-01-01 03:10

In Java, we can directly use String to declare a string variable name and specify its value. We do not have to define the string as an array by using new keywor

10条回答
  •  -上瘾入骨i
    2021-01-01 03:39

    String str = “This is string literal”;

    This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “This is string literal”, then str will reference of that string and no new String object will be created.

    String str = new String(“this is string created by new operator”);

    This is string object. In this method JVM is forced to create a new string reference, even if “this is string created by new operator” is in the reference pool.

提交回复
热议问题