Вопрос

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 ?

Это было полезно?

Решение

== 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.

Другие советы

As everyone replied:

  • "" checks for empty String.
  • null checks for null reference.

Use StringUtils from apache commons to eliminate two conditions. StringUtils.isEmpty(yourVariable) this condition will handle both cases.

"" --> indicates empty String in Java. Rather than using userReorderSelection == "" it is preferable to us

userReorderSelection.isEmpty() // But make sure that userReorderSelection is not null


null --> indicates Null references (can be reference of any object)

If you do not have this check it may result in NullPointerException if you try to use this reference. Empty String will not throw such exceptions.

== null checks to see if the object reference is null. == "" checks to see if the object reference equals a blank string

str.equals ("") checks to see if your String object contains the empty string.

I guess what you want is

if (userReorderSelection == null || userReorderSelection.equals (""))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top