-3

I dont thnk i should ever use String.intern() in jdk7 and + ,Because of following reasons.
Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.
Since interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String()

String s1 = "Rakesh";

String s2 = "Rakesh";
String s3 = "Rakesh".intern();
String s4 = new String("Rakesh"); // why would i do this?
String s5 = new String("Rakesh").intern(); // looks stupid , better create like s1

s1,s2, s3 ,s4 point to same thing.

Your comments plz

Not a bug
  • 4,286
  • 2
  • 40
  • 80
user93796
  • 18,749
  • 31
  • 94
  • 150
  • 1
    **s1,s2, s3 ,s4 point to same thing.** No it doesn't .Do System.out.println(s3 == s5); and System.out.println(s2 == s4); .Better understanding of String will help you understand difference between all objects. – rns Mar 24 '15 at 11:43
  • 3
    There are pretty few reasons to use intern() at all. In 18 years of Java programing I never encountered a situation where it was useful. I did see it used once, and there it was used wrongly, hurting performance. – Thomas Stets Mar 24 '15 at 12:13
  • @ms , it was s1,s2,s3 and s5 . not s4 – user93796 Mar 25 '15 at 10:03
  • why is my question downvoted ?The question is very clear with examples and its a useful question – user93796 Mar 25 '15 at 10:04

2 Answers2

1
String s3 = "Rakesh".intern();

This does nothing - the String object that represents the string literal is already in the string pool, so intern() does nothing here but just return the string that is already in the pool. It's the same as String s3 = "Rakesh";

String s4 = new String("Rakesh"); // why would i do this?

There is no reason ever to create a String object in this way, by passing it a string literal to the constructor. String objects are immutable and it is never necessary to explicitly create a copy of a string literal in this way.

String s5 = new String("Rakesh").intern(); // looks stupid , better create like s1

You already answered this yourself in the comment.

My advice: Forget about the intern() method - or keep it somewhere far away in the back of your mind. You don't need this method in 99,9% of the Java programs you are going to write. This method is only useful for very specific, rare occasions.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

Just read the Java doc please.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115