How to handle null in Pattern.compile? - java

How to handle null when using Pattern.compile? I'm using the following line to compare strings:
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()
There are some cases where s1 can be null and obviously it throws NullPointerException. I know this could be handled by another if condition to s1, but I would like to know is there's an alternate solution.
EDIT
Iterator iter = sampleList().iterator();
while (iter.hasNext()) {
SampleObj so = (SampleObj) iter.next();
if (!s1.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s1), Pattern.CASE_INSENSITIVE).matcher(so.getS1()).find())
match = true;
else
match = false;
}
if (!s3.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s3), Pattern.CASE_INSENSITIVE).matcher(so.getS3()).find())
match = true;
else
match = false;
}
}
s1 and s3 are inputs which are matched over iterator.

You have to check for null; e.g.,
if(s1 != null && Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()))

Pattern.matcher() will always throw a NullPointerException when you pass in null, so: no, there is no other way, you'll have to check for null explicitly.

I use
String.valueOf(s1)
which results in having "null" instead of null.

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 to compare an Integer using least code?

There is an Integer property called foo in a model. Now I need to know whether it equals 1 or 2. Usually I use:
if (null != model) {
Integer foo = model.getFoo();
if (foo != null) {
if (foo == 1) {
// do something...
}
if (foo == 2) {
// do something...
}
}
}
Is there any handier code to avoid the NullPointerException?
You can use Optional:
Optional.ofNullable(model)
.map(Model::getFoo)
.ifPresent(foo -> {
switch (foo) { // or if-else-if, the important thing is you skip the null check
case 1:
...
break;
case 2:
...
break;
...
}
});
You can use the null-safe java.util.Object.equals:
if(null != model) {
Integer foo = model.getFoo();
if(Objects.equals(foo, 1){
//do something
}
if(Objects.equals(foo, 2){
//do something
}
}
The method has this description:
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
If you didn't return null sentinels values, and instead used Optionals, you could do:
Optional<Model> model = getModel();
Optional<Integer> foo = model.flatMap(Model::getFoo);
foo.filter(Integer.valueOf(1)::equals).ifPresent(this::doSomething);
foo.filter(Integer.valueOf(2)::equals).ifPresent(this::doSomethingElse);
You could do Integer.of(1).equals(foo), but this is a bit silly. Why save the one line? I'd just put it inside the same if/else-if chain (and if that gets long, conside a switch/case (which also is not null-safe, though).
if (foo == null)
else if (foo == 1)
else if (foo == 2)
Also note that comparing objects with == is a bit tricky because of how auto-boxing works (or does not work). I think that it works in this case, but I do not want to have to think about it too hard, so in my code I usually drop down to int (after the null check) to be on the safe side.
Assuming possible value is only 1 or 2
Of course the model the should be guarded with null check
Use ternary operator
Model theModel = model.getFoo() ;
if(model!=null && model.getFoo()!=null){
model.getFoo() == 1 ? callOne() : call2();
}
Edit the code to like this:
if (null != model) {
Integer foo = model.getFoo();
if (Integer.valueOf(1).equals(foo)) {
// do something...
}
if (Integer.valueOf(2).equals(foo)) {
// do something...
}
}
I hope to help you.

java for loop that runs list executes only once

The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null
For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.
if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}

Check if EditText with "inputType = number" is null

I am trying to check if the input in EditText in null or not .
if(editTextSum.getText().toString() != null) {
userStartingBalance = Integer.valueOf(editTextSum.getText().toString());
} else {
userStartingBalance = 0;
}
Here userStartingBalance is Integer type .
But I am getting an error everytime that
Can't convert " " into int , and the line is pointed to the 'if case' if I don't enter anything.
Why is it not going to else case?
What should be the workaround?
You are not properly handling the case in which your EditText simply has no content in it.
In this case, editTextSum.getText().toString() will not return null (in fact, that should never be null). Instead, it will return an empty string.
Instead, you might want to try editTextSum.getText().toString().isEmpty() instead,. isEmpty() will return true if the length is 0.
try:
Integer.parseInt(editTextSum.getText().toString())
Why is it not going to else case ?
Because you are calling ToString() on Null. If the field has no value present then it wil set NULL to it and if you try to run the toString() method you will receive this error. Do the Null check before retrieving the value.
Workaround
if( editTextSum.getText() != null )
{
userStartingBalance = Integer.parseInt(editTextSum.getText().toString());
}
else
{
userStartingBalance =0;
}

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