Search code examples
javaif-statementnullis-empty

Confuse "==null" and "==" "" in java?


I have a simple issue related ==null and =="" ,i think everybody know this issue .

Here's an example:

@SuppressWarnings("unchecked")
public void reorderingCriteia() {
    ListModelList<ReorderData> headerList = new ListModelList<ReorderData>();
    List<String> headerId = new ArrayList<String>();
    String userReorderSelection = Services.userPreferenceService().getUserPreference().getUserOption("PROCESS_CHECKLIST_COLUMN_REORDER");

    if (userReorderSelection == null || userReorderSelection == "") {
        int i = 0;
        for (ReorderData rd : availableReorderList) {
            headerList.add(rd);
            headerId.add("" + i);
            i++;
        }

        folderProcessModel.setHeaderList(headerList);
        folderProcessModel.setHeaderId(headerId);

    } else {
        headerList = ReorderDialogViewModelNew.jsonStringToList("FOLDER_PERMIT_LIST_COLUMN_REORDER", userReorderSelection, false);
        headerId = compHelper.intializeSequnce(headerList, folderProcessModel.getAvailableHeaders());
        folderProcessModel.setHeaderList(headerList);
        folderProcessModel.setHeaderId(headerId);

    }
}

I have some questions:

  1. Here this code use if (userReorderSelection == null || userReorderSelection == ""). Can i use this condition if (userReorderSelection == null) ?

  2. What is the difference between two ?


Solution

  • == null checks for null reference.

    == "" check for blank/empty string reference. Here you could use str.equals("") to check if the string is empty/blank or not. == is used for object reference checks. Or you can use the String.isEmpty() to check the same.

    Also, if you use just if (userReorderSelection == null), then you'll only be checking if the userReorderSelection is null or not and it won't determine whether the String is empty or not.