0

I created a document called doc.txt, and in it I wrote "blaha". I wrote a program to see if it says blaha.

    File file = new File("C:/Users/Public/doc.txt");
    if (file.exists()){
     FileReader fr = new FileReader(file);
     LineNumberReader ln = new LineNumberReader(fr);
        while (ln.getLineNumber() == 0){
          String s = ln.readLine();
          System.out.println(s);
          if(s=="blaha"){
              System.out.println("Match");
          }else{
              System.out.println("Nomatch");
          }
    }
    }

And when I run the program, it always says Nomatch. Why is this?

Pete B.
  • 3,188
  • 6
  • 25
  • 38
user1797443
  • 236
  • 1
  • 5
  • 15

3 Answers3

6

To compare strings for value equality (whether two objects have the same value) do this:

s.equals("blaha")

The == operator tests for reference identity (whether two objects are one and the same). Most of the time, you're interested in equality.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Because blaha != trollface. Also, you're going to want to make that more robust to handle trailing white space. You probably want to use trim() on the string. Also, use String.equals() or string.contains().

Dodd10x
  • 3,344
  • 1
  • 18
  • 27
0

First of all always use .equals. No ifs and no buts. Read this for details: http://www.coderanch.com/how-to/java/AvoidTheEqualityOperator

systemhalted
  • 818
  • 9
  • 24