-1

Possible Duplicate:
Java String.equals versus ==

The main code:

String pass = getPassowrd();
    if(pass == "hi"){
        System.out.println("Correct Password");
        loggedin = true;
        new Home();
    }else{
        System.out.println("Incorrect Password");
    }

The getPassword code:

private static String getPassword() {
    java.util.Scanner keyboard = new java.util.Scanner(System.in);
    return keyboard.nextLine();
}

What am I doing wrong?

Thanks, Isaac

Community
  • 1
  • 1
Isaac
  • 56
  • 7

2 Answers2

2

You are comparing references, use .equals for checking String content, replace

if (pass == "hi") {

with

if (pass.equals("hi")){
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

do a pass.equals("hi") instead of pass == "hi"
With an == operator what you are really comparing are the references, i.e. you are comparing the value in pass which is just an address to the string that it is pointing in the memory and another address that points to the constant string "hi" that is stored in the memory.

With equals you are actually comparing the string "hi" with the string that pass is pointing to in the memory.

vijay
  • 2,646
  • 2
  • 23
  • 37