Where are the s.substring (1) and "j" objects stored in general, because we obviously did not store them in any variables.
"j" is a literal (string constant), respectively, when the class is loaded, it is automatically interned and goes to the pool of strings, where it is stored. The string will contain the link from the class in which it is declared, respectively, it will not be available to the garbage collector until the class itself is unloaded from the virtual machine.
s.substring(1) - creates a new object, the link to which is not stored anywhere. Dynamically created strings are collected by the garbage collector, like any other objects. By the way, with such a call will be selected a string without the first letter, and not the first letter.
Creating new objects can be tracked using this code (Dynamically created string can be forced to put into the pool using the String.intern method.):
String s = "hello"; //false, строка такая же, но substring создает новый объект System.out.println(s.substring(0,1)=="h"); //false, оба раза substring создает новый объект System.out.println(s.substring(1,2)==s.substring(1,2)); //true, получили ссылку на строку из пула System.out.println(s.substring(0,1).intern()=="h"); //true, поместили строку в пул System.out.println(s.substring(1,2).intern()==s.substring(1,2).intern());
Dynamically created strings pooled are stored in a heap ( starting with JDK7 ) and are available to the garbage collector.
What happens to these strings after the method works, whether they are destroyed by the garbage collectors, since, for example, if this is in the body of the loop and at each step s.substring () will create strings that! Equals () between themselves ( so that there are different lines in the pool), then this is a waste of memory.
In the cycle, new objects will be created each time, which will be available to the garbage collector. The behavior for strings in this case is similar to the behavior for any other objects.
Related questions in English: