0
import java.util.*;
import java.lang.*;

class password
{
    public static void main(String[] args)
    {
        int i;
        String pass,temppass;
        Scanner s=new Scanner(System.in);
        System.out.println("Enter Password: ");
        pass=s.next();
        System.out.println("Re-enter password: ");
        temppass=s.next();
        if(temppass==pass)
        {
            System.out.println("Sucess");
        }
        else
            System.out.println("failed");
    }
}

I wrote this basic code in Java to match my password input. Even if I enter the correct password, it goes to the else statement, i.e. "failed". What should I do now?

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

1

String or any other object must always use the equals method to check for equality.

You are using temppass == pass which is incorrect.

You should use temppass.equals(pass) to compare the two strings.

Here is the correct way to do it:

class password
{
    public static void main(String[] args)
    {
        int i;
        String pass,temppass;
        Scanner s=new Scanner(System.in);
        System.out.println("Enter Password: ");
        pass=s.next();
        System.out.println("Re-enter password: ");
        temppass=s.next();
        if(temppass.equals(pass)) // This is how equality must be checked 
        {
                System.out.println("Sucess");
        }
        else
                System.out.println("failed");
    }
}

Update:

The == operator compares object references and not values.

So when you perform temppass == pass, it is comparing if both variables are pointing to same object which is not the case. They're pointing to two different objects in memory (despite both objects containing same value). Thus the check returns false.

On the other hand, the equals method checks for the value of the objects and if the values match, it returns true.


Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
1

This is where the problem lies:

if(temppass==pass)

You have to use equals method for string comparison.

The == operator compares the value of two object references to see whether they refer to the same String instance.

The equals() method compares the value inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not.


Source: What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Jomoos
  • 12,823
  • 10
  • 55
  • 92