Java - String - Comparison

Asked

Viewed 222 times

2

I’m not getting a simple comparison I’m making, but it’s not performing like I think it should.

Situation

I request that the user type the person’s name, and capture with String nome = scan.next();

And send to this function :

// FIND PESSOA
private boolean findPessoaInList(String nome){
    Boolean _return = false;
    for(Pessoa p : this.pessoas){
        if(p.getNome() == nome){
            _return = true;
            // return true;
        }
    }
    return _return;
}

to check whether the person is already registered.
Yet never falls inside the if even if the name already exists in the list.

Code getNome in Pessoa

public String getNome() {
    return nome;
} 

If anyone could explain to me what’s going on, I’d appreciate it.

  • You have considered using the equals method instead of the operator ==?

  • I didn’t even remember this method sorry, I always programmed in PHP and javascript in which comparison is made with == or ===

1 answer

3


If you use == it will compare with memory addresses, if you want to compare only the values use the .equals(). Another attention is on case sensetive, if you type some lower case letter and use equals the other capital will give false, to avoid this use equalsIgnoreCase()

String nomeMinusculo = "maicon";
String nome = "Maicon";

System.out.println(nomeMinusculo == nome); // false
System.out.println(nomeMinusculo.toUpperCase() == nome.toUpperCase()); // false
System.out.println(nomeMinusculo.equals(nome)); // false
System.out.println(nomeMinusculo.toUpperCase().equals(nome.toUpperCase())); // true

/* Sugerido pelo Filipe Gonzaga */
System.out.println(nomeMinusculo.equalsIgnoreCase(nome)); // true

Ideone Exemplo

In your case

// FIND PESSOA
private boolean findPessoaInList(String nome){

    // remover espaços a direita e esquerda
    nome = (nome == null) ? "" : nome.trim();

    Boolean _return = false;
    for(Pessoa p : this.pessoas){
        if(p.getNome().equalsIgnoreCase(nome)){
            _return = true;
            // return true;
        }
    }
    return _return;
}
  • 1

    Use String.equalsIgnoreCase instead of toUpperCase() - if the intention is to ignore case sensitive.

  • 1

    @Filipegonzagamiranda Updated with your suggestion, thank you.

  • 1

    Magina @Maiconcarraro, we are here to share real knowledge! :)

Browser other questions tagged

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