Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the representation of the empty line?  RSS feed

 
Taras Lukiyanets
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String[] args) {

try {
File myFile = new File("E:\\workspace\\config.txt");
BufferedReader reader = new BufferedReader(new FileReader(myFile));
String line = null;
while ((line = reader.readLine()) != null) {
if (line == "")
System.out.println("---");
System.out.println(line);
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

So I want eventually to catch the empty line. In the while loop I compare 'line' with "" and guess what, nothing happens - the program never prints "---"! Despite the fact that debugger in such moments shows [ line="" ].
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use String.equals() to compare Strings, not ==.
 
Taras Lukiyanets
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, 'line.equals("")' works fine, thanks!
Just being curious, can you also tell why '==' doesn't work, thought not indicating any error?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== compares two references to see if they are pointing to the same object in memory.

equals() is a method in the Object class that does exactly the same thing. However, many classes in java override this method to provide more logical functionality. In the case of String, the equals() method returns true if both objects are Strings and contain exactly the same sequence of characters.
[ August 30, 2006: Message edited by: Joanne Neal ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!