Hi all In the K&B book it was mentioned that String literals are put in "String constant pool" ,so they can be shared by various objects. So given the following: String s1 = new String("abc");LINE 1 String s2 = new String("abc"); s2 = s2.intern(); // LINE 3 System.out.print( s1 == s2 ); // prints false; I want to know why it prints false ( the result is the same with or without LINE 3 ), is this mean that the String constructor's argument "abc" isn't put in the pool? But in K&B books there is an example similar to LINE 1 and they say that two objects are created s1 and "abc" in the pool. So can some one explain what's going on here? Thanks in advance Alexan [ May 26, 2003: Message edited by: Alexan Kahkejian ]
it returns false because s1 is not in the stringpool
s1 = "abc" than the result would be true.. or s1.intern() == s2.intern() -> also true..
Joined: Apr 30, 2003
Thanks Robert But I want to know if "abc" will be put in the pool with ( new String("abc") )constructor. And How many objects are created by the following line of code? String s1=new String("abc"); K&B Book says that two objects are created, but if "abc" is not in the pool only one object is created. can someone help me? Alexan [ May 26, 2003: Message edited by: Alexan Kahkejian ]
First time the JVM encounters that "abc" is used in the program creates a string object and interns it. From then all the subsequent "abc" expressions refer to the very same string object. The same is true for every string object representing the same sequence "abc" if interned. One advantage: comparing interned string objects with == is much faster than with equals. [ May 26, 2003: Message edited by: Jose Botella ]
I don't imagine it makes much difference since the very first line in the String equals() method returns true if the objects are equal by ==. So basically you have the overhead of making a method call and thats it. Bill
Joined: Jul 03, 2001
Thanks Bill, I think I read what I said somewhere and I just trusted it.
One advantage: comparing interned string objects with == is much faster than with equals.
Jose, I think this is what you meant: Comparing string references is much faster than comparing the contents of String objects that have not been interned. You might have read this from The Java Programming Language 9.3
However, any two strings with the same contents return the same String object from intern, which enables you to compare string references to test equality, instead of the slower test of string contents.
Dealing with the results of intern makes comparing object references equivalent to comparing string contents, but much faster.