Problem with string comparison

Asked

Viewed 351 times

1

I need to compare if the name typed in textField is equal to the "root" user. At the time of comparing even typing root the Eclipse informs that it is invalid. Unfortunately I don’t understand the reason for the mistake.

// ...
            model.Usuario mUser = new Usuario();

            // Enviar Usuario e Senha
            String tfUser = tfUsuario.getText().toString().trim();
            char[] tfPassword = tfSenha.getPassword();
            mUser.setUser(tfUser);
            mUser.setPassword(tfPassword);

            // ...
            if(tfUsuario.getText() == "root") {
                JOptionPane.showMessageDialog(null, "Válido", "Aviso", 0);
                System.out.print(tfUsuario.getText());
            } else if(tfUsuario.getText() != "root") {
                JOptionPane.showMessageDialog(null, "Inválido", "Aviso", 0);
                System.out.print("Nome do Usuário: " + tfUsuario.getText());
            }
  • That’s why I score negative?

2 answers

4


Use the method equals() to compare Strings in Java. As the String in java is an object, when you use == compares the memory address of the object:

Ex:

if("texto1".equals("texto2")){

}
  • 1

    Allan, Many thanks my noble.

1

One should always use the equals() when comparing the value of Strings.

Use == brings confusion of this kind:

String nome1 = new String("Marcela");
String nome2 = new String("Marcela");

System.out.println(nome1 == nome2); //false

String nome3 = "Marcela";
String nome4 = "Marcela";

System.out.println(nome3 == nome4); //true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.