-5

how to move heap area data to String constant pool ?

        String s3 = new String("Test");
         final String s4 = s3.intern();
         System.out.println(s3 == s4);//fasle(i need true)

i dont want to create new object so just cut the object from heap and paste it in String constant pool

trincot
  • 317,000
  • 35
  • 244
  • 286
Shivaraj Mc
  • 25
  • 1
  • 6
  • `System.out.println(s3.equals(s4))`. In other words, don't compare references, compare the data. I don't see that there's _ever_ a need to compare `String` references (other than to `null`), and if you think you have a need for it, you have probably designed your program wrong. To answer your question, `s3.intern()` creates a new object and thus the references will _never_ be equal. – ajb Sep 30 '16 at 05:40
  • i dont want to create new object so just cut the object from heap and paste it in String constant pool . – Shivaraj Mc Sep 30 '16 at 06:04
  • Almost everything in Java is an object. Java is not Microsoft Word, and you can't just "cut and paste" data without creating a new object. You really need to go back and study the fundamentals of Java. – ajb Sep 30 '16 at 06:09

1 Answers1

0

You are not moving heap data to the String constants pool when you call intern, you are just adding another new String to the constants pool if it doesn't already exist in the constants pool (which doesn't happen in your case as "Test" is already added to constants pool in line -1).

You might want to change your code to :

public static void main(String[] args) {
    String s3 = new String("Test");
    s3 = s3.intern();
    String s4 = "Test";
    System.out.println(s3 == s4);//fasle(i need true)
}

In the above code you assign the reference to the interned value of s3 to s3 again. Next,you get the same object from String constants pool in S4.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • i want move(cut) the heap area data to String constant pool?but when am using intern just it copy the object.. – Shivaraj Mc Sep 30 '16 at 05:46
  • i dont want to create new object so just cut the object from heap and paste it in String constant pool – Shivaraj Mc Sep 30 '16 at 05:47
  • @ShivarajMc - Well, once the GC runs, the String `Test` which is on heap will be eligible for GC. Thus you are indirectly doing a cut-paste of the same object with some delay – TheLostMind Sep 30 '16 at 05:47
  • @ShivarajMc - You can't "move" an object from one place to another (JIT can do it if it wants to though). – TheLostMind Sep 30 '16 at 05:50
  • your correct.... ("Test" is already added to constants pool in line -1) – Shivaraj Mc Sep 30 '16 at 06:23