1

I have one object of String as new String("abc"); How will i convert that object to String pool Object

3 Answers 3

3
   String str=  new String("abc").intern() // calling intern() will add the String object to the String pool. 
Sign up to request clarification or add additional context in comments.

6 Comments

But remember to use the return value of intern instead of new String("abc") afterwards, otherwise, you will not operate on the interned string!
"abc".intern() please. So the string is not created twice.
@Vakh: But "abc".intern() is crap. String literals are interned anyway. Okay, new String("abc") is more crap :). The simplest solution for interning "abc" would be just "abc".
@gexicide I agree. new String(someString) is just ugly.
so please suggest me which one is better ?
|
1

If your object is really new String("abc"), then you should just use "abc" instead of creating a new string and interning this one. "abc" is interned anyway, as all string literals are.

I.e., the below boolean operation will be true

"abc" == new String("abc").intern()

1 Comment

makes sense.. "abc" will already be added to the String pool.
0

Well, you don't convert a String to a StringPool. StringPool is a collection of strings managed by the JVM. You can, however, request a string to be included in the pool by requesting the VM to do so using intern() method of the String object if it has not been created as a literal (otherwise it is already there)

   String test= "test".append("Case").append("String");
   test.intern(); //string "testCaseString" will be interned

   String check= "InternString";
   check.intern(); //redundant as the string was already interned in the above creation statement

3 Comments

so intern() is not usefull ?
Of course it is usefull if you create or build your string or obtain it from an object where you do not know how it was created. It is only redundant if the string was created as a literal
Okay Thank u Satyan Raina :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.