permaculture playing cards*
The moose likes Beginning Java and the fly likes null strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null strings" Watch "null strings" New topic
Author

null strings

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
I want to open a text file and read in the lines until there are no more lines to read. So I have commands that look something like this:

try{
BufferedReader reader = new BufferedReader(new FileReader("importantfile.txt"));
line = "not null";
while (line != null){
line = reader.readLine();
doImportantStuff(line);
}
reader.close();
}catch(IOException ex){
ex.printStackTrace;
}

But I am wondering, won't this stop reading lines as soon as a blank line is read? What is the difference between these?

String line = null
String line = ""

And if line==null, will this give you an error?
int x = line.length();
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Kevin Tysen:
...What is the difference between these?

String line = null
String line = ""

And if line==null, will this give you an error?
int x = line.length();

"" is an empty String (an object). But "null" means that the variable has no object to point to. So what happens when you try to dereference a null value?


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I suspect your loop is not going to do what you want. Try to "play computer" and imagine an empty file. The first read gives you a null. What happens as it is written?


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Thank you!
 
jQuery in Action, 2nd edition
 
subject: null strings