0

I've just started to learn java, and I met some confusing codes:

   String s0 = new String("tava");
   System.out.println(s0 == s0.intern());

   String s1 = "hava";
   String s2 = new StringBuilder("ha").append("va").toString();
   System.out.println(s2 == s2.intern());

   String s3 = new StringBuilder("ga").append("va").toString();
   System.out.println(s3 == s3.intern());

   String s4 = new StringBuilder("lava").toString();
   System.out.println(s4 == s4.intern());

   String s5 = new StringBuilder("ja").append("va").toString();
   System.out.println(s5 == s5.intern());

The results are:

   false
   false
   true
   false
   false

My jdk is 1.8, I want to know the details about how it runs in JVM(heap, stack and constant pool) to make out why the results will be like these.

  • 2
    **Never** call `new String()` (and this is why). The lone `true` is because `"gava"` ***didn't*** exist in the `intern` pool before `s3` was created ("java" does at `s5`). And don't compare `String`(s) with `==` (but if you want `true`, put the `intern` calls on the LHS). – Elliott Frisch Jun 23 '16 at 02:42
  • I get something else: `false false true false true ` – Thilo Jun 23 '16 at 02:48
  • @Thilo at least that's consistent. I got the same result as OP. – shmosel Jun 23 '16 at 02:50
  • Seems on your JVM run `"java"` was already interned, but not on mine. – Thilo Jun 23 '16 at 02:51
  • @ElliottFrisch: Why would putting `intern` on the other side make a difference? `x == x.intern()` will always evalute to the same as `x.intern() == x`. – Thilo Jun 23 '16 at 02:56
  • @Thilo I wasn't paying enough attention (or perhaps I wasn't being clear enough, it's late here); but I was really trying to say ***add*** an `intern` call to both sides (with two separate references) if you want to test for `String` equality with `==` (`x.intern() == y.intern()`; which is a terrible idea anyway, so forget I suggested it and just use `x.equals(y)`). – Elliott Frisch Jun 23 '16 at 03:02

0 Answers0