milind k das wrote:When String reference varialble is assigned to hardcoded literal, it will still be treated as String object holding literal value.
No. A reference variable NEVER holds a literal. Reference variables ALWAYS hold references. If you assign a string literal to a variable of type String, Java simply creates an object for that string literal (but only once per distinct literal) and assigns a reference to that String object to the variable. In the image you attached you can see that s1 and s3 are both references that point to the same String object.
for example. String s1 = "Welcome to Java" ---Here "Welcome to Java" should be treated as Strong object holding "Welcome to Java" literal.
No. s1 should be treated as a variable that holds a reference to an object that is equal to "Welcome to Java".
In the s3 its an object holding literal.
Again, no. s3 is a variable that holds a reference to an object that is equal to "Welcome to Java". But because the programmer used the same string literal they used for s1, s3 and s1 simply refer to the same String instance.
Why does s1, s3 not treated as objects while s2, s4 are treated as separate objects?
None of s1, s2, s3 and s4 are objects. They are all variables. They all hold references to objects. Which objects they refer to depends on whether you used a string literal or not.
Variables that were assigned the same string literal will refer to the same object. Variables that aren't assigned a string literal will refer to separate objects, unless you explicitly assigned them a reference to an interned string. You can do this in two ways:
milind k das wrote:. . . which constructor in String class . . . create object . . . String s1 = "Welcome to Java"
None. The JLS (=Java® Language Specification) tells you that, “At run time, a string literal is a reference to an instance of class String (§4.3.3) that denotes the string represented by the string literal.”
and which constructor incase of String s2 = new String("Welcome to Java"). ?
This one, which I think it is usually mistaken to use because String is an immutable type.
Why are only string literal hardcoded are treated like "intern" way? Why not the Objects created with new keyword?
Because the instance created from a constructor has no existence before the code is executed. Because the constructor's documentation as above says it, “Initializes a newly created String object . . . a copy of the argument string.” They acknowledge that it may not be necessary to create a copy of a String object, but supplied fuinctionality to conver all possibilities, including that somebody might want a copy of a String object.
Thank you. I will be doing more reading for understanding. I have another question.
What is the difference between inheritance and object instantiation(then using the instantiated object)? They both seem to be performing same tasks. What's need for inheritance when using objects itself are helping in achieving the tasks?