Comparing string array in JAVA - java

I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks

You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.

You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.

String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))

you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}

Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}

Try this:
if(DATA != null && Data.coord[i].equals(Data.search))

Related

Nullpointer Exception while using WebSocket and MySQL [duplicate]

There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both

Check whether list object is null in java

I'm checking whether a List object is null or not using java. But I'm not sure whether it is the optimized way or not.
Here is my code:
List<String> listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
The above line itself throws null pointer exception.
if(listSCBPLNewErrMsgs != null) <Right way?>
This will get all the values from the config.
Now, tomorrow if I change the config entry, this should not throw an null pointer exception
The new operator in Java can never return null. Neither can String#split.
What you may want to check, however, is that the list is not empty:
if (listSCBPLNewErrMsgs.isEmpty()) {
// do something
}
If SCBPL_NEW_ERRORMESSAGES is null that code will still fail.
Assuming that SCBPL_NEW_ERRORMESSAGES has some value or is empty, the split will return an array of size 0 or more. Changing it to a list from an array will yield either an array with 0 or more elements.
Lastly, the copy constructor will copy the content and assign it to a new list. In all scenarios, unless there is a null pointer on SCBPL_NEW_ERRORMESSAGES, the returned list (listSCBPLNewErrMsgs) will never be null, at most it will be empty, which can be checked with the isEmpty() method call.
As per your comment, if you are getting a null pointer on that line, it should be due to the fact that SCBPL_NEW_ERRORMESSAGES is null.
Try this:
List<String> listSCBPLNewErrMsgs = null;
if(SCBPL_NEW_ERRORMESSAGES != null) {
listSCBPLNewErrMsgs= new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
}
else {
listSCBPLNewErrMsgs = new ArrayList<>();
}
If you want to check whether it is null it is right way (even though it will never be null), however if you simply want to check if list is empty then you should use isEmpty() method:
if(listSCBPLNewErrMsgs.isEmpty()) {/**/}
From the looks if your code your listSCBPLNewErrMsgs object won't be null. Test if it is empty using the listSCBPLNewErrMsgs.isEmpty();
If SCBPL_NEW_ERRORMESSAGES is nulll that will throw a NPE exception indeed since you will be using the split method on null.
You can first check if that's not null:
if (SCBPL_NEW_ERRORMESSAGES != null) {
//Instantiate list
//Optional isEmpty check
}
You will first check if SCBPL_NEW_ERRORMESSAGES is not null
Then you can instantiate your list and perform an optional isEmpty check on the new list.
if(SCBPL_NEW_ERRORMESSAGES != null)
List<String> listSCBPLNewErrMsgs= new ArrayList<String>Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
No Need of listSCBPLNewErrMsgs != null as everyone said
First you have to check SCBPL_NEW_ERRORMESSAGES is null or empty
if(!TextUtils.isEmpty(SCBPL_NEW_ERRORMESSAGES))
You have to check both whether the list is null/empty or not. So I prefer
if(listSCBPLNewErrMsgs != null && !listSCBPLNewErrMsgs.isEmpty()) {
}
You need to add null check for SCBPL_NEW_ERRORMESSAGES.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
In your declaration, list can not be null as your are doing new ArrayList<String>.
So no need to worry about null pointer exception.
If you wish to check for empty list.
Then you can try isEmpty() method.
if (SCBPL_NEW_ERRORMESSAGES != null && !SCBPL_NEW_ERRORMESSAGES.isEmpty()) {
List<String> listSCBPLNewErrMsgs = new ArrayList<String>(Arrays.asList(SCBPL_NEW_ERRORMESSAGES.split("\\$\\#")));
if (!listSCBPLNewErrMsgs.isEmpty()) {
// Do something.
}
}

!array[0].isEmpty() returning NullPointer?

Here's my code:
if (!quizDescs[0].isEmpty()) {
mDescText.setText(quizDescs[0]);
} else {
mDescText.setVisibility(View.INVISIBLE);
}
So, when this code runs, and the if condition returns true, everything is fine and dandy, however, if it returns false, it says there's a NullPointerException, and points me to the line of code containing the if statement.
Am I checking the condition right? Why is it returning a NullPointer?!
ANSWER:
if (quizDescs[0] == null) {
mDescText.setVisibility(View.INVISIBLE);
} else {
mDescText.setText(quizDescs[0]);
}
if quizDesc[0] is String, you can do
if(!StringUtility.isEmptyOrNull(quizDesc[0])){
mDescText.setText(quizDescs[0]);
}else {
mDescText.setVisibility(View.INVISIBLE);
}
By the way,
Null and being empty is not same
Consider
String s; //Initialize to null
String a =""; //A blank string
Its always a good practise to use
try{
//Your code here..
}catch(Exception e){
e.printStacktrace();
}
If either quizDescs or quizDescs[0] are null, you'll get a NullPointerException.
Obviously, if isEmpty() returns false, it means that isEmpty() was executed, so quizDescs[0] is not null when the condition returns true, and that's why it works.
Either make sure that both quizDescs and quizDescs[0] is never null, or change the condition to :
if (quizDescs != null && quizDescs[0] != null && !quizDescs[0].isEmpty()) {
....
} else {
....
}
You have an error because quizDescs is Null so when you try to get quizDescs[0] in the condition, you try to get the first item of null object.
The only possible ways the if-line can cause a NullPointerException, is when quizDescs itself is null or the first element quizDescs[0] is null. Try to extract quizDescs into a local variable for debugging purposes and inspect its content.
You can either initialize your array with empty strings or add a check for null - or better review your logic how null is a possible condition. Usually null values should be avoided (see Bloch, Effective Java 2nd Edition, item 43 for a similar case).

NullPointerException when comparing with null values in java [duplicate]

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
Closed 8 years ago.
if(status.equals(null))
{
status="Pass";
}
from above code it throws NullPointerException, please give solution for comparing value with null.
Looks like status itself is null. So when you do:
status.equals("null")
You're actually doing:
null.equals("null")
Which causes NPE. You should do:
if(status == null) //Now you're checking if the reference is null
//So you'll never dereference a null pointer
You might find this link useful.
Related topics:
What is null in Java?
Java null check why use == instead of .equals()
In Java "null" is a string. You want to compare the reference to null. Do the following:
if(status == null){
// code here
}
Keep in mind that String is class in Java.So whenever you call a method with unitialized object (which is a null object) then it will throw NullPointerException.In your case, there is possibility that your String status is not initialized So you need to make it sure.
BTW you should check null without using equals() method because it doesn't make sense that you are checking a null object's method for its null value.
You must do like this
if(status == null)
//Do something
only use equals method when you want to compare a String and at the stage where you are quiet sure that your String is initialized.Let say String status = ""; is a intialized String and now it is not null.Just for the info while using equals() , try to use it like "anyValue".equals(status) instead of status.equals("anyValue") because by using like "anyValue".equals(status), it will be more safe in case of null string and you wont get NullPointerException
if(status.equals("null")) //Just checking if string content/value is same
{
status="Pass";
}
By this you are just checking if value(content) of status variable is "null" String or not. IF you want to do a null check you need to do the following
if(null == status)
{
status="Pass";
}
You are not suppose to make it null as "null"! in your case compiler consider it as string.
if(stringVariable!=null)
{
//ur Code
}
(OR)
if(stringVariable.equals(null))
{
//Ur code
}
In case if ur working with string array you can do it as following
if(stringArray.isEmpty())//checks length of String array
{
//ur code
}
You cannot use .equals with a null . Use :
if(status == null) {
//Do something
}
This is exactly the reason why the HashMap cannot store more than one null values . Because it always compares the key with other valuues and if a null is inputted the second time , it throws NPE .
You are getting this error since status is null.

Nullpointer exception

There is a possiblity that this may be a dupicate question.
I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
If you use
if (x == null)
you will not get a NullPointerException.
I suspect you're doing:
if (x.y == null)
which is throwing because x is null, not because x.y is null.
If that doesn't explain it, please post the code you're using to test for nullity.
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.
String is immutable
#Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
#Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}
I am comparing s==null only
can you show the code snippet that you have written
s==null will never throw a NPE
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both

Categories

Resources