• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null strings

 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic