I created a program To return if a String entry is equal to "password". Sort of a password program. As you can see from the output the entry and expression are both equal. Why then does it print wrong??

package Main;
import java.io.*;
 class password
   {
       public void password() throws IOException
       {
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
           System.out.println("enter the password");
           String entry = br.readLine();
           System.out.println("printing the entry: " +entry);
           String password = "abc";
           if (entry== password)System.out.println("Correct");
           else System.out.println("Not a match");
        }
    }

output:
enter the password
>abc
printing the entry: abc
Not a match

Please rectify the program and suggest a better method of doing it

When it comes to reference types, == compares references and not the actual objects. If you want a logical comparison (equal check), use the equals method of the String class. Read Javadocs for more details.

When it comes to reference types, == compares references and not the actual objects. If you want a logical comparison (equal check), use the equals method of the String class. Read Javadocs for more details.

Please elaborate

The equality operator compares references.

String str = "hello";
String anotherStr = str;
System.out.println(str == anotherStr); // true

If case you need logical equality check, use the equals method of the String class.

String line = readLine(); // user enters 'mypassword'
String pwd = "mypassword";
System.out.println(line == pwd); // false
System.out.println(pwd.equals(line));  //logical equality; true

If it's still confusing, I'd highly recommend you read the excellent tutorials available at Sun along with the book Head First Java.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.