0

I am making a side project in Java where a Mobile will store a list (ArrayList) of apps and separate UI class to handle all input/ output and business related logic. The problem is in following block of Mobile class:

public App searchApp(String name)
{
    System.out.println(list);
    for(App app: list) {
        String appName = app.getName();

        if(appName == name)
        {
            return app;
        }
   }

   throw new IllegalStateException();
}

This function let person search for the app in the list. And here's how the search input is being taken from user:

public String inputSearch()
{
    System.out.println("Enter app name to search: ");
    return sc.nextLine().trim();
}

And here's how the UI class is displaying result:

public void choices(int choice)
{   
    switch(choice)
    {
        case 1:
            String[] input = inputDetails();
            mobile.addApp(input[0], input[1]);
            break;

        case 2:
            String s = inputSearch();
            App found = mobile.searchApp(s);
            System.out.println("App found in search:");
            System.out.println(found.toString());
            break;            

and so on...

The problem is in searchApp.

I am unable to figure out why if condition is not working even though both appName and name can be seen as equal upon printing (also have used trim() on both string types but still no success).

Abhinay
  • 11
  • 4

2 Answers2

0

Since the name is a String, you need to use .equals() to check equality (instead of ==). Using == checks that they are the exact same object, but using equals checks if their contents is the same.

So the correct way would be:

 if(appName.equals(name))
    {...
Adib Faramarzi
  • 3,798
  • 3
  • 29
  • 44
0

While the above answer points out the main problem, one could still improve by using some explicit/implicit null checking by doing something like

StringUtils.equals(appName, name).

Otherwise if appName is null you'll get an ugly NullpointerException ;-)

Markus Fried
  • 96
  • 1
  • 10