viktor.
viktor.

Reputation: 11

How do i compare an attribute from a class with a string?

How do i properly write the third line? I have an array zivali that contains name, surname and other attributes. I need to compare only the Name (ime) attribute from each zivali array element. Is it with equals, = or == and how can i properly write it? Thank you all, looking forward to your answer

public boolean zivalObstaja(String ime) {
    for(int i=0; i<zivali.length; i++) {
        **if(zivali[i].ime==(ime))** {
        return true;
        }
    }
    return false;
}

Upvotes: 0

Views: 698

Answers (2)

Dumidu Udayanga
Dumidu Udayanga

Reputation: 914

There are three ways to compare string in java

  1. By equals() method

    The String equals() method compares the original content of the string.

  2. By == operator

    The == operator compares references not values.

  3. By compareTo() method

    The String compareTo() method compares values and returns an integer value that describes if first string is less than, equal to or greater than second string.

Since you want to compare the original content of the string. You have to use first one.

public boolean zivalObstaja(String ime) {
    for(int i=0; i<zivali.length; i++) {
       if (zivali[i].ime.equals(ime)) {
          return true;
       }
    }
    return false;
}

Upvotes: 0

ruohola
ruohola

Reputation: 24107

You need to use String.equals:

if (zivali[i].ime.equals(ime)) {

Upvotes: 1

Related Questions