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.