• Post Reply Bookmark Topic Watch Topic
  • New Topic

strings and string pool  RSS feed

 
Vinney Shanmugam
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between declaring,

String test = "string testing";

and

String test = new String("string testing");
 
Devaka Cooray
Marshal
Posts: 5650
765
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have mentioned the difference in the subject line.
In other words, the second statement always create a NEW String object, while the first statement may take an existing String object from the String pool.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even worse, the second line does both. It takes a string out of the string pool (creating it if necessary) and then creates an exact copy of it. The String API also mentions this:
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote: . . . The String API also mentions this . . .
Vinney Shanmugam, you should by now be used to looking in the API documentation. And noticing where the documentation tells you not to use a construct.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!