0

I read

String s = new String("Hello")

will create two object one in heap and other one in String Pool.

But how can we check and confirm that exactly 2 Objects get created.(I am using Eclipse)

hitz
  • 1,100
  • 8
  • 12
sparsh610
  • 1,552
  • 3
  • 27
  • 66
  • 1
    As a rule of thumb, never use the String constructor with literal strings. I also wonder why you would want to check this? – LionC May 22 '15 at 13:56
  • @LionC and i wonder why you are here ? might be for learning ... so am i .. – sparsh610 May 22 '15 at 13:57
  • I think more than he needs to use String constructor, what he needs to learn is how to check the created number of objects. – Randika Vishman May 22 '15 at 13:57
  • I understood your question and appreciate that you want to learn :-), I just wanted to note that if you are doing that with the String constructor in an actual application, you likely should change it. Do you want to know how to find out how many objects were created after specifically a String constructor call or after some constructor call in general? – LionC May 22 '15 at 14:03
  • No, i am not using it in current application.And yeah i want to know how to find out the number of object created for any constructor(including String). – sparsh610 May 22 '15 at 14:07
  • Check this link (Counting Objects Clandestinely): http://www.javaspecialists.eu/archive/Issue038a.html. Hopefully this will help u. – Bacteria May 22 '15 at 14:15
  • Well, String class doesn't allow us to listen when its constructors have bean executed, But based on this answer http://stackoverflow.com/a/22098863/1393766 you could try altering your JVM and change String class to add some code which would inform you each time its constructor has been called or what was result of intern method. – Pshemo May 22 '15 at 14:21

1 Answers1

0

Actually it won't always create two objects as the String "Hello" may already be in the String pool.

Either way, in order to check you should use something like jmap -heap (which comes with the jdk) before and after. It will show you heap summaries.

I assume this is an academoc exercise btw. As LionC comments, you shouldn't ever construct Strings in this way.

Phil Anderson
  • 3,146
  • 13
  • 24