javastring

In Java, why is String a non-primitive data type?


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 keyword, even though String is non-primitive data type.

Can someone please explain why String is non-primitive datatype?


Solution

  • String str = “This is string literal”;
    

    This is a string literal. When you declare a string like this you are actually calling intern() method on String.

    This method references an internal pool of string objects. If there already exists a string value “This is string literal”, then str will reference that string and no new String object will be created.

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

    This is a string object. The JVM is forced to create a new String reference, even if "this is string created by new operator" already exists in the reference pool.