-2

I am writing a simple program to get to grips with using the Scanner in Java. The program has a stored value for user_1 and asks the user to provide the String variable username which is then checked against user_1 using the == operator, however even when username matches user_1 it still evaluates to false. I'm sure I must be missing something simple, any help would be appreciated. I even added the line printing both variable just to double check they are the same!!

import java.util.Scanner;

public class HelloWorld {

public static void main(String[] args) {

    String user_1 = ("lucasRHCP");

    Scanner input = new Scanner(System.in);
    System.out.println("Enter your username: ");
    String username = input.nextLine();

    System.out.println(user_1 + " " + username);

    if (username == user_1){
        System.out.println("True");
    }
    else {
        System.out.println("False");
    }
}   
}
LucasGracia
  • 125
  • 11

3 Answers3

2

NEVER compare objects (and String is am object) with ==, use equals() method

Germann Arlington
  • 3,315
  • 2
  • 17
  • 19
2

With == you compare whether two objects are the same, not whether their value is. You want to compare their values, so you need to use .equals():

if (username.equals(user_1)) {
  System.out.print("True");
} else {
  System.out.print("False");
}

It's like comparing two red identical looking car, they are identical but not the same thing. In java two variables can be both the same thing or two distinct, alike things.

s-ol
  • 1,674
  • 17
  • 28
0

You can't compare Strings in java using ==

You should use the String class methods

username.equals(user_1);
Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73