Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String declaration  RSS feed

 
janardhan rao B
Greenhorn
Posts: 9
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

At the time of declaration of a string value which is the better way from below two.
1. String value = null ;
2. String value = " " ;
And please give me some explanation on them.

Regards
Janardhan.B
 
Callum Ludwig
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess option 1.



As option 2 would in fact create 2 objects in memory. The first is the empty string which is assigned to the String Pool and then the String reference variable.

So if you're hard up for memory then option 1 is the way to go, as it would only create 1 object in memory and that would be the String reference variable.

Also other parts of your program can then check for null to find out if the variable was initialized or not.



But the above is not really an issue as you can check for an empty string, I was just dribbling more stuff to fill up this post with.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
janardhan bommineni wrote:At the time of declaration of a string value which is the better way from below two.

It's impossible to answer that question because the two statements are not doing the same thing. The first one is initializing the variable to null, the second one to a String object that contains a single space character. Maybe you meant to write "" instead of " ", but an empty string is still not the same as null.

Callum Ludwig wrote:As option 2 would in fact create 2 objects in memory. The first is the empty string which is assigned to the String Pool and then the String reference variable.

So if you're hard up for memory then option 1 is the way to go, as it would only create 1 object in memory and that would be the String reference variable.

No. There is only one String object involved, the String object that represents the literal " ". Note that variables in Java are references - they are not objects themselves.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper's right. What value do you want it to have? That's the value you should give it. Context is everything.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!