JAVA object string count

Can anyone explain questions 87 and 89 at this link http://www.javatpoint.com/corejava-interview-questions-3

87) How many objects will be created in the following code?

String s1 = "string1";
String s2 = "string1";
String s3 = "string1";

      

Answer: only one object

89) How many objects will be created in the following code?

String s = new String("Welcome");  

      

Answer: two objects: one in the string persistent pool and the other in the non-pool (heap).

+3


source to share


3 answers


Although it String

is a class written in Java, it is a kind of special class that has a special relationship with the JVM. One is a string literal (a sequence of characters wrapped in quotes). When the JVM sees it "abc"

, it does something like the following:

String obj = stringLiteralsCache.get("abc");
if (obj == null) {
    obj = new String("abc");
    stringLiteralsCache.put("abc", obj);
}

      



So in the first example, the first line causes a new instance to be created, but the next two lines just get the already created instance from the cache.

However, the cache only works with literals. It cannot prevent the creation of a new instance when the constructor is called explicitly. Thus, new String("Welcome")

creates 2 objects: one from the literal Welcome

because it is not yet in the cache, the second from an explicit call to the String constructor.

+6


source


The first syntax ( String string1= "string1";

) creates only one String object for any define String .. = "....";

and one reference variable pointing to it. The object is created in a pool of String constants maintained by the JVM. In the second case String s = new String("Welcome");

, two String objects are created. Since new is called, one String object is created in normal memory. In addition, the string constant "newstring" will be put into the String constant pool.

So when we don't have a new keyword, we only have one String object in the pool of String constants.



More info in: Create new lines in regular memory and in a row pool

+1


source


The basic principle is that strings are irrevocable in Java. This means that once created, they cannot be changed.

This allows the JVM to do optimizations. So a good JVM will optimize (87) the creation of a single object. But bad may not be. There is nothing attractive to the JVM for this kind of optimization. The JLS does not require this.

So a reasonable answer to (87) is probably 1, but not more than 3.

(89) is more difficult. In most cases, you will find that one object is created in the global row pool and the second (due to usage new

) is created in regular memory. However, I see no reason why this cannot be optimized for just one row s s

by referencing the global row pool directly.

So a reasonable answer to (89) is probably 2, but it could only be 1.

+1


source







All Articles