• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which one is better way to create a String object.  RSS feed

 
yogendra singh
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1 = new String("hello");
OR
String s2 = "hello";
and why ???
what are the inner step behind to make String object
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first one always creates a new String object; every time this line is executed, a new String will be created. The String referenced in the second version will be shared among all uses. So unless you have some specific need to create physically distinct String objects, the second form is better.
It's almost never necessary to use the String constructor that takes a String argument.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!