Dear Friends #1 I am facing a few problems with the intern() method of the String class. When exactly is it invoked? Can you please guide me or direct me to a online resource or a book which explains this. #2 About compile time and run time activities - again, please guide me to a resource (online, book, etc.) Thanx regards Sanjeev
About intern() method: IMHO the best way to find out when it is invoked is to look at the code for String class. It is invoked by NO String method. My conclusion: intern() is only invoked when JVM deals with String literals, like String s = "abc"; - intern() will be invoked. But after String s = new String("abc"); s will not be interned.
I agree with Mapraputa Is. Actually most of the methods of String which return String i.e. toString() substring(0) concat("") toLowerCase() trim() ... and even replace('x','x') are cleverly written so that if the String which is about to be returned is same as the one the method was invoked on, then the String object on which the method was invoked is returned. I was living with the Idea that this happens because of intern method(). Must thank Mapraputa for pointing it out.
[This message has been edited by mohit joshi (edited September 30, 2000).] [This message has been edited by mohit joshi (edited September 30, 2000).]
That�s an interesting question. My first reply is not complete. When is a String interned? From Jane� quote: �All literal strings and string-valued constant expressions are interned�. What are �string-valued constant expressions�, JLS mentioned? I tried a small program:
The last case is the most interesting. As mohit joshi said , expression "c".trim() doesn�t create a new object, it returns reference to �c� literal.
Nevertheless, the whole expression with �c�.trim() is not interned. I think we do not need to know all that for the exam, just curious.
Leverager of our synergies
Joined: Aug 26, 2000
Still thinking about this question�
[This message has been edited by Mapraputa Is (edited October 01, 2000).]
subject: Help needed on intern(), compile time Vs run time