-2

This is my Java code to read text from a text file

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class checking {
public static void main(String[] args) throws IOException {

// Create a BufferedReader from a FileReader.
BufferedReader reader = new BufferedReader(new FileReader("pw.txt"));

// Loop over lines in the file and print them.
while (true) {
    String line = reader.readLine();
    if (line == null) {
    break;
    }

    System.out.println(line); // The output is abc
    if(line=="abc"){
        System.out.println("true");
    } else {
        System.out.println("false"); //However it show false...
    }
}

// Close the BufferedReader.
reader.close();
}
}

Inside pw.txt, there is only one line which the only text in there was abc.
I did an if statement to check if the line is equal to "abc" however the output was false... which I don't quite understand.
Did I made any stupid mistakes?

Bsonjin
  • 438
  • 1
  • 4
  • 14

3 Answers3

1

This is the huge mistake beginners to java makes please refer http://www.javatpoint.com/string-comparison-in-java site on what is the difference between == and .equals() in java

Neenad
  • 861
  • 5
  • 19
0

Change the way you compare 2 Strings:

if (line.equals("abc")) {
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

Use line.equals("abc") instead of line=="abc"

Ref : What's the difference between ".equals" and "=="?

Community
  • 1
  • 1
Rahman
  • 3,755
  • 3
  • 26
  • 43