• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

What is the representation of the empty line?  RSS feed

 
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="" ].
 
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!