Saturday, 3 June 2017

In Java, Why String is 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?


Answer





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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...