String comparison problem [duplicate]

0

I need to compare if the name entered in the textField is the same as the "root" user. When comparing even by typing root Eclipse informs you that it is invalid. Unfortunately I do not understand the reason for the error.

// ...
            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());
            }
    
asked by anonymous 11.06.2018 / 14:01

2 answers

4

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

Ex:

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

}
    
11.06.2018 / 14:05
1

Always use equals() when comparing Strings .

Using == causes confusion of this type:

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
    
11.06.2018 / 14:42