How to turn null into false in Java? - java

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;

Related

Java 8 Optional: combine two possibly null object

I have to ensure if two values are non null. When the first and second have non null values, pass first as argument to second. If one of them are null value, then return false.
This can be done in the following piece of code:
String value1 = function_to_get_value1()
if (value1 == null) return false;
String value2 = function_to_get_value2(value1)
if (value2 == null) return false;
return true;
It can also be done in short form:
try {
return function_to_get_value2(function_to_get_value1()) != null;
} catch (NullPointerException e) {
return false;
}
I was wondering how to do this in fluent form with Optional.
You could try something like this:
return Optional.ofNullable(function_to_get_value1())
.map(v1 -> function_to_get_value2(v1))
.isPresent();
map() applies the lambda if value is present and returns a new Optional.ofNullable() or otherwise returns an empty Optional. So in the end you have an empty Optional if either value was null or a non-empty one.
If you have a look at the source code for those methods, it basically is equivalent to this:
//Optional.ofNullable(...)
Optional<UiObject> v1Opt = value1 == null ? Optional.empty() : Optional.of(value1);
//Optional.map(...)
Optional<UiObject> v2Opt;
if(v1Opt.isPresent()) {
//this is the lambda
UiObject value2 = function_to_get_value2(value1);
//Optional.ofNullable(...) called in map(...)
v2Opt = value2 == null ? Optional.empty() : Optional.of(value2);
} else {
v2Opt = Optional.empty();
}
//Optional.isPresent()
return v2Opt.value != null;

how do i make arrays equal if they have to be filled?

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.

Redundant if in code block

I have following checks on input json and schema. I use intelliJ and it's static code analysis is saying condition shcema != null is always true.
if (json == null && schema == null){
return;
}
if ((json == null && schema != null) || (json != null && schema == null)){
throw new InvalidRequestException("error message");
} else try {
JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(schema);
ProcessingReport processingReport = jsonSchema.validate(json);
...
} catch ( ... ) { ... }
Now, if i don't put in the first if condition where i am checking both objects, i might miss a use-case where its okay not to provide anything. Thats why i am using return in first if and not an exception.
What am i missing here
Your first if statement checks if json and schema are both null and then in the second if statement you check whether one of them is null, right?
Well then the second if can be simplified to:
if (json == null || schema == null){
Why? Because at this point, if we know that json is null, then schema must not be null (or else it would have returned). Similarly, if we know that schema is null, then json must not be null (for the same reason).
By the way, if you want to check whether two boolean values are "different", use the XOR operator ^:
if (json == null ^ schema == null) {

Android: Can't check whether a string variable is null or not. How to check if a string variable is null or not?

I can't check whether a string is empty or not coming from rest service as input stream which then I am changing into string for parsing.
public boolean isNullorEmpty(String string)
{
if(string !=null || !string.isEmpty() || string.length()>0)
return true;
else
return false;
}
Please help me out to check if string is empty or not.
The current problem in your code is that if the string you pass in argument is null, thenstring !=null is evaluated to false. Hence you'll try to evaluate !string.isEmpty() which will lead to a NullPointerException.
On the other hand if you pass a String that is not null (ex "" or "test"), string != null is evaluated to true and hence you return true.
So to fix that you should, as the name of your method suggests, check if the String is null OR empty.
But since you're on android, don't reinvent the wheel and use TextUtils.isEmpty(CharSequence str).
boolean isEmpty = TextUtils.isEmpty(myString);
Returns true if the string is null or 0-length.
If you want to look about how is it implemented:
427 public static boolean isEmpty(CharSequence str) {
428 if (str == null || str.length() == 0)
429 return true;
430 else
431 return false;
432 }
Well, this can be handled in plain java like:
And it can be written like:
public boolean isStringEmpty (){
if(str ==null || str.isEmpty () || str.trim().equals("")){
return true;
}
return false;
}

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:
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 (""))

Categories

Resources