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:
Here this code use if (userReorderSelection == null || userReorderSelection == ""). Can i use this condition if (userReorderSelection == null) ?
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 (""))
Related
i am confused because I need my array to be equal to the other array but I don't know how to compare them without losing their values
If both roots are null you will get an undesired result based on what you're trying to do with your second if condition.
It looks like if both roots are null you want to return true, but you're returning false. You could use just one if statement
if(thisRoot == null || otherRoot == null){
return thisRoot == null && otherRoot == null;
}
You have a bigger problem with how you're comparing the data of the two nodes.
thisRoot.getData() != otherRoot.getData()
This comparison is not what I think you're looking for. Instead you should overrride the equals method for your data objects and compare using it instead
The order of your conditions causes a problem.
if (thisRoot == null || otherRoot == null) {
return false;
}
if (thisRoot == null && otherRoot == null) {
return true;
}
The first condition will evaluate to true (and lead to return false) even if both branches are null.
You should first evaluate if both branches are null; after that, you can check the case where only one of them is null.
I have the below method call.
If name or desc is null, it uses the word null. Instead I would like an empty string.
How to achieve this as part of the method call itself. I don't want to do this outside of the method call with if conditions.
boolean creatok = users.create (String.valueOf(name), String.valueOf(desc));
boolean creatok = users.create (Objects.toString(name, ""), Objects.toString(desc, ""));
I think you should use conditions, if you want to avoid 'if' clauses, use a ternary operator
boolean creatok = users.create(name == null? "" : String.valueOf(name), name == null? "" : String.valueOf(name));
You can do something like this if you don't want to write if else
boolean creatok = users.create (name == null ? "" : name, desc == null ? "" : desc);
In my code I have a org.apache.tapestry5.json.JSONObject named j.
I want to read the property use-name from that Object:
Boolean isUseName = (Boolean) j.opt("use-name");
The value can either be true, false or null (if the entry is not present in the JSONObject). Now I'd like to use isUseName for a conditional statement:
if(!isUseName) {System.out.println("No Name to be used.")}
This gives me a NullPointerException if "use-name" was not in the JSONObject. One way is to simply check first if isUseName is null, e.g.
if(isUseName != null && !isUseName) {System.out.println("No Name to be used.")}
I was wondering, if there is a more elegant way. Is it e.g. possible to (automatically) set isUseName to false, if j.opt() returns null? One thing that came to my mind is using a ternary expression, but this has a redundant j.opt("use-name"):
Boolean isUseName = (j.opt("use-name") != null)
? (Boolean) j.opt("use-name")
: false;
You could compare with Boolean.TRUE:
boolean useName = Boolean.TRUE.equals (j.opt ("use-name"));
Logical expressions short-circuit, so if you check null first, then you can use it after the check:
if(isUseName != null && !isUseName) {
// It's not null, and false
System.out.println("No Name to be used.");
}
or
if(isUseName == null || !isUseName) {
// It's null or false
System.out.println("No Name to be used.");
}
and similarly
if(isUseName != null && isUseName) {
// It's not null, and true
}
and
if(isUseName == null || isUseName) {
// It's either null or true
}
How about check if the key exists
boolean useName = j.has("use-name") ? j.getBoolean("use-name") : false;
I have written some code; here the relevant snippets:
#NonNullByDefault
public class Score<NUMERAL, LITERAL>
{
protected NUMERAL value;
#Nullable
protected LITERAL literal;
[...]
I have overwritten my equals()method as follows:
#Override
public boolean equals(#Nullable Object object)
{
if(object == null) return false;
if(object == this) return true;
if( object instanceof Score)
{
return ((Score<NUMERAL, LITERAL>) object).getValue().equals(value) &&
literal == null ? ((Score<NUMERAL, LITERAL>) object).getLiteral() == null : literal.equals(((Score<NUMERAL, LITERAL>) object).getLiteral());
}
return false;
}
Basically, the idea is that a Score may only have a numeric value in which case the literal is null. I have written some unit tests and get a null pointer exception with the code below:
[....]
Score<Float, String> score = new Score<>(0.0f);
Score<Float, String> anotherScore = new Score<>(1.0f, "One");
[....]
assertFalse(score.equals(anotherScore));
If I am not mistaken, shouldn't short-cutting in equals prevent anything after the && from being executed as the first expression is already false? Furthermore, why the exception? As the conditional is true, I would expect the expression of the ternary to be evaluated and the conditional expression skipped. From what I have read in the specifications, this should be the behaviour. Furthermore, I found this question: Java ternary (immediate if) evaluation which should lend some more leverage to my thought process.
Maybe I have overlooked something rather obvious but I am out of ideas. Maybe you can help?
It short-circuits alright, but not quite the way you want it to. && has a higher precedence than the ternary ?: - therefore this (indentation, line breaks and comments added to clarify)
((Score<NUMERAL, LITERAL>) object).getValue().equals(value) &&
literal == null
? ((Score<NUMERAL, LITERAL>) object).getLiteral() == null
: literal.equals(((Score<NUMERAL, LITERAL>) object).getLiteral())
actually means this:
//the first line as a whole is the condition for ?:
((Score<NUMERAL, LITERAL>) object).getValue().equals(value) && literal == null
? ((Score<NUMERAL, LITERAL>) object).getLiteral() == null
: literal.equals(((Score<NUMERAL, LITERAL>) object).getLiteral())
This means, in practice, that if the first part of the condition is false but literal is null, you automatically enter the : part of the expression where you call literal.equals, causing the NullPointerException.
The fix is simple: add parentheses to tell Java which way you want stuff to be evaluated:
((Score<NUMERAL, LITERAL>) object).getValue().equals(value) &&
(literal == null
? ((Score<NUMERAL, LITERAL>) object).getLiteral() == null
: literal.equals(((Score<NUMERAL, LITERAL>) object).getLiteral()))
I want to check for null or empty specifically in my code. Does empty and null are same for StringBuilder in Java?
For example:
StringBuilder state = new StringBuilder();
StringBuilder err= new StringBuilder();
success = executeCommand(cmd, state, err);
/* here executeCommand() returns empty or null in state, I cant make changes in <br/> executeCommand() so can I check it in my code somehow for state, if its null or empty? */<br/>
if (state == null) { //do blabla1 }
if (state.tostring().equals("")) { //do blabla2 }
Does above code make sense or how should I change it?
No, null and empty are different for StringBuilder.
StringBuilder nullBuilder = null;
if(nullBuilder == null) {
System.out.println("Builder is null");
}
&
StringBuilder emptyBuilder = new StringBuilder("");
if(emptyBuilder == null || emptyBuilder.toString().equals("")) {
System.out.println("Builder is empty");
}
In Java, null is a reference literal. If a variable is null then is not referring to anything.
So, if you have StringBuilder s = null, that means that s is of type StringBuilder but it is not referring to a StringBuilder instance.
If you have a non-null reference then you are free to call methods on the referred object. In the StringBuilder class, one such method is length(). In fact if you were to call length() using a null reference then the Java runtime will throw a NullPointerException.
Hence, this code is quite common:
If (s == null || s.length() == 0/*empty if the length is zero*/){
// do something
It relies on the fact that evaluation of || is from left to right and stops once it reaches the first true condition.
Null mean, there are no object in the heap for that reference variable. This is common to all java object, not specific to StringBuilder and Empty means, "".
In your code, you have created a StringBuilder object, so checking null is redundant. And, You can check empty by using isEmpty() method in from java String api
if(state.tostring().isEmpty()) {
//
}
And checking null is correct. Find the corrected version here
if (state == null) {
// ...bla 1
} else if (state.tostring().isEmpty()) {
//... bla 2
}
Your second if condition will throw NullPointerException, if the state is null. So if should be nested with if else
No. empty means, that there are no characters in the StringBuilder. null means that there is no StringBuilder object at all.
A variable is only null if it has a reference type (for example String, StringBuilder, Set, as a thumbrule: all capitalized types) and it is not initialised yet or has been set explicitly to null.
The below code may help you,
StringBuffer sb = new StringBuffer();
String str = sb.toString();
if(!"".equals(str)) {
System.out.println("String : " + str);
} else {
System.out.println("Empty Builder");
}
You can try like this
StringBuilder state = new StringBuilder();
if(StringUtils.isNotBlank(state .toString())){
//this will check for null, " ", ""
}