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) {
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.
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 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 (""))
My code looks like below,
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null){
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
I have handled NUll pointer for the caseX and also for getter and when null set the bigdeciaml to a default ZERO value. Still I get Null pointer exception in the setter line.Any suggestions?
It's quite possible that caseXObj is null, so it'll cause the NullPointerException. You should test the three cases like this:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if (caseXObj != null && caseXObj.getCaseInGrossAmt() != null) {
// do something with caseXObj
} else if (caseXObj == null) {
// initialize caseXObj, you were misssing this case!
} else {
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
In essence, the error was that you were testing for only two cases - and there are three of them.
Assuming it is OK for getCaseXDao() to return null, you need to assign to caseXObj rather than use it as a pointer in the else clause.
That because you don't check for null in your else part.
It should be:
caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null)
{
//...
}
else
{
if (caseXObj != null)
{
caseXObj.setCaseAmt(BigDecimal.ZERO);
}
}
Are these comparisons always safe from creating a NullPointer Exception ?
if( myObject == null || myObject.someMethod() == someValue )
{
if( myObject == null && myObject.getAlwaysTrue() )
{
}
}
Is there some directional precedence in java for condition evaluation, apart from short circuiting ?
UPDATE: I Know myObject.anything() will throw a NullPointer. Its just that I have come across such code by other programmers, and I want to know if there's a safe way of squeezing multiple checks along with a null check in a single condition. I'm looking for a good rule to stick to.
No, this line is not safe:
if( myObject == null && myObject.getAlwaysTrue() )
If you know that myObject is null then you shouldn't try to dereference it. If however you wrote this:
if( myObject != null && myObject.getAlwaysTrue() )
Then it would be safe. This is because && (and || for that matter) has short-circuit evaluation. If you write a && b and the expression a evaluates to false, then the expression b is not evaluated so it will not throw an exception. The left operand is always evaluated first.
Why not separate out the gating issue?
if (myObject != null) {
if ((myObject.someMethod() == someValue) && myObject.getAlwaysTrue()) {
}
}
if( myObject == null && myObject.getAlwaysTrue() )
This will cause you a NullPointerException when myObject is null
Wherever I can, I strive for less indentantion and complex "ifology". In your case I'd just write
if (myObject == null) return;
... go on knowing that myObject is not null...
If the myObject is null, myObject.getAlwaysTrue() in the second if statement will always result in NullPointerException.
In the case of || the if expression evaluates the boolean expressions until it finds the first one that's true.
With && the if expression evaluates the boolean expressions until it finds the first one that's false.
So in your case when myObject is null, you'll get the following evaluations:
First if:
myObject == null -> true
Second if:
myObject == null -> true
myObject.getAlwaysTrue() -> NullPointerException
This is not :
if( myObject == null && myObject.getAlwaysTrue() )
&& will check both conditions, myObject.getAlwaysTrue() will throw NullPointerException if myObject is null.