Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA string number of objects [closed]

Tags:

java

Can any one explain Question 87 and 89 from 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 is : only one object

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

String s = new String("Welcome");  

Answer is : Two objects, one in string constant pool and other in non-pool(heap).

like image 566
Mayank Pandya Avatar asked Jan 10 '23 11:01

Mayank Pandya


2 Answers

Although String is a class written in Java it is a kind of special class that has some special relationships with JVM. One of them is string literal (sequence of characters wrapped by quotes). When JVM sees "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 your first example the first line causes creation of the new instance but next 2 lines just get the already created instance from cache.

However cache works on literals only. It cannot prevent creation of new instance when you explicitly invoke constructor. So, new String("Welcome") creates 2 objects: one from literal Welcome because it is not in cache yet, second from explicit invocation of String constructor.

like image 62
AlexR Avatar answered Jan 15 '23 11:01

AlexR


The main tenet here is that strings are immutable in Java. That means that once created, they cannot be changed.

This allows a JVM to make optimisations. So a good JVM will optimise (87) to the creation of one object. But a poor one may not. There's nothing compelling a JVM to make such an optimisation. The JLS does not demand this.

So the sensible answer to (87) is probably 1, but no more than 3.

(89) is more difficult. In most cases you'll find one object being created in the global string pool and a second one (due to your using new) being created in normal memory. However, I can see no reason why this couldn't be optimised to just one string with s referring to the global string pool directly.

So the sensible answer to (89) is probably 2, but just might be 1.

like image 23
Bathsheba Avatar answered Jan 15 '23 13:01

Bathsheba