This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
Good question. public String replace(char oldChar, char newChar);
a) - If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. b) - If oldChar and newChar are identical then a reference to this String object is returned.
c)Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar
In first case you invoke "String".replace('t', 't'), Here since oldChar and newChar in call to replace are identical a reference to exisinting "String" object is returned. Further since "String" is a literal that is used in your code , and as you know Strings are immutable and hence JVM the following will happen. a. JVM will create a new String object in String pool for the string literal used in your code. b. Due to above explanation , replace() will return the this string object and since this string object ["String"] is already in the String pool a reference to it is returned and hence the result is equal in first case.
Now coming to second case since oldChar and newChar are different in both the calls to replace a new string object is created in both the cases even though the final string is same. The JAVADOC API says that a new string object will be created.
Hi Thanks Mr.Deepal Jain for giving a good explanation.
I want to know that from where you got all this type of deeply knowledge .Mostly books do not cover these in so much detail even K&B . I am planning to give exam on 19 january ,but i do not have so deep knowledge like you.Please tell me from where should i read them or it is must required so deep knowledge to give test. I am doing practice on whizlab but i never found a question like this as above. Please guide me .
Waiting for your reply [ January 08, 2008: Message edited by: pradeep singh ]
very good question anil & thanks deepak for good explanation
Joined: Aug 05, 2006
Hey, My name is Deepak and not Deepal I don't have any deep knowledge in Java and my aim is gaining more and more knowledge by participating in java forums. When i saw this question, the first thing i did was run the code and second thing i did was read the Java API doc for the method and after that i understood the concept and explained .
For exam i would say you will need 3.5 hrs of complete concentration and offcourse some knowledge of Java thats the way i took my exam on Dooms day of 2007 Just keep reading and keep practicing. All the best for your exam. [ January 09, 2008: Message edited by: Deepak Jain ]