0
public class llearning1 {

    public static void main(String[] args) {

        String text = "is";
        String x = "what is good";
        String y[] = x.split(" ");

        for (String temp: y) {

            if (temp == text) {
                System.out.println("found");
            } else {
                System.out.println("nothing");
            }
        }
    }
}

output:

expected : code should display "found"

but it is displaying "nothing"

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
user3197241
  • 45
  • 1
  • 2
  • 5

2 Answers2

1

Compare the String with equals() method not with == operator

== operator is used to compares the reference of the object.

change if (temp == text) to if (temp.equals(text))

Nambi
  • 11,944
  • 3
  • 37
  • 49
0

String is Object and object equality checks with .equals() method.

so try:

if(temp.equals(text))

== operator is used for object reference comparison means two reference is pointing to the same object or not or primitive(int, double, ...) value comparison.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110