• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the difference between NULL and " "

 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between NULL and " ".Are the below assignments same?

String str1=NULL;
String str2=" ";


thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64717
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There no such thing as NULL; it's null.

null means no reference. "" is a string literal representing a String object.
 
Maneesh Godbole
Saloon Keeper
Posts: 11021
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To give an example

#1 There is no baby name because there is no baby
#2 There is no baby name because it is not named yet, the baby does exist though
 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks all.

Which is the proper way to initialize the string



or


 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have initialized strings both ways in the past.I did not realise both are different.Which is the proper way?
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, "String str1=NULL" it certainly ain't, because, as Bear said, there is no such thing as NULL in Java. The answer depends entirely on the context of your app. Maneesh has already pointed out how the two ways might be interpreted differently. Note that initializing a String to " " -a single space- is very unusual. The empty string -""- is much more common.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did not realise both are different.

Here's a very important question, then: What do you think "null" means? I'm baffled how one could think that it's the same as a one-character string.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12100
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
saying

String str1 = " ":

gives you a String object that has one character in it - that character is a space. You have a box, and there is something in the box.

saying

String str1 = "";

gives you a String object with no characters in it. It's like having a box with nothing in it.

saying

String str1 = null;

gives you no String object. You have a name for your box, but you don't have a box.
 
Monica Shiralkar
Ranch Hand
Posts: 842
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for spelling null as NULL. Its a typing mistake.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic