Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of default String constructor

 
Inder Kumar Rathore
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any body tell me what is the use of default constructor of String class,
I know we can create empty string from it but where to use that empty string...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API says :
Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.
 
Inder Kumar Rathore
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it really necessary to initialize it.....we can initialize it wit null also...

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you make a String, you want to assign a value to it once. Remember that it's immutable. If you need to use null, String str = null is enough.
 
Rob Spoor
Sheriff
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inder Kumar Rathore wrote:Is it really necessary to initialize it.....we can initialize it wit null also...

That's not the same. new String() is the same as "", not null.

But I agree that the default constructor is never really needed from code, just like the constructor that takes another String. Both are remainders of old times and may still be used in reflection, but other than that they should be shunned.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic