I do not think that there is any difference. I believe that
Sring temp ="hello"; is also interned by the JVM by calling the intern() method to send it to constant pool
OR probably, the argument from String temp = new String("hello") is used to call intern() method for interning the constant to string literal pool.
The change is not made in bytecode as javap did not show this when I looked. Actually, I am not very confident on this, Java Language Specification - String Literals might be of help.
The best question should have been, though: How and when should I use intern() method?
The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in
Joined: Jul 07, 2012
I do not think that there is any difference
That is the reason this doubt arised.If there is no difference then why is intern used?
There is no difference between calling intern() on a string literal and using the string literal itself, that's true. But consider what happens when you call intern() on a value which isn't a string literal.
Joined: Jul 22, 2013
calling intern method on string literals doesn't make any change.
Non-literals will become literals when intern is invoked on non-literals.
Monica. Shiralkar wrote:I understand that there is difference between using string Intern method and creating string as String temp=new String("hello");
But I am not able to understand difference between using string intern and creating string as Sring temp ="hello".
The fact is that you rarely need to use intern(), and almost never with straight literals. If you're combining strings, however, you can use it to see if the combination has already been created; although in many cases, that's so unlikely that you're just wasting CPU cycles.
The CachedObjects page contains some examples that might be helpful.
Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here