Monday, October 02, 2006

Java String - What is there to discuss?

Java String presents lots of confusion if you really do not understand the basics very tightly. Look at the following two statements:

Statement 1
String s1 = "hello world";

Statement 2
String s2 = new String( "hello world" );

Wha is the difference between the above two statements?

Statement 1 means: String variable s1 refers to a string "hello world" in the string pool maintained by JVM. Thus, JVM first searches for the string "hello world" in the string pool. If it finds one, it returns the reference to the string. If it does not find, it creates an entry "hello world" in the string pool.

Thus, next time, you create String s3 = "hello world", variable s3 points to alreasy existing "hello world" in the string pool.

Statement 2 means: A new object is created on the heap and the reference to it is passed to variable s2.


Post a Comment

<< Home