0

I am high school java learner,went through a lot of discussions but still not getting clarity on the below question. The String intern function says that if String object is not present inside String pool it will create one and returns reference to it.Can there be a case when a created String object with new operator i.e. String s=new String("def"),it is not present in the String pool before interning? If not,why does the definition of intern() is like this? Thanks

ZerekSees
  • 91
  • 1
  • 10
  • 2
    All String literals go to the string pool. You have a string literal `"abc"`. – Kayaman Apr 07 '17 at 10:51
  • OK.Can there be a case when you have a string object on heap and for the same string value ,it is not present inside the String pool.The intern function says"if not present ,it will creteate String in the String pool".So it can never be like a String object is on heap but not in String pool. – ZerekSees Apr 07 '17 at 10:53
  • Of course. If you construct a string without using string literals, then the resulting string will be on heap, but not in the string pool. – Kayaman Apr 07 '17 at 10:58
  • @Kayaman String str=new String("def"); here "def" is not present on String pool ,,,right? – ZerekSees Apr 07 '17 at 11:06
  • No, I said **without** string literals. You have a string literal `"def"` there. – Kayaman Apr 07 '17 at 11:06
  • OK.How to create String object without literals?Is this possible? – ZerekSees Apr 07 '17 at 11:09
  • With a `char[]` for example. – MC Emperor Apr 07 '17 at 11:29
  • `String str = new String("def");` The literal `def` is in the pool, the String `str`, created by `new` is not in the pool. `str == "def"` will result in false, Another way to create a String: `String def = "d"; def += "ef"` or some method like `"Xdef".substring(1)`. – user85421 Apr 07 '17 at 13:20

0 Answers0