How to access NULL value - java

while(i<word.length)
{
ans=swn.extract(word[i], pos[i]);
if(ans== null)
polarvalue[i]= " ";
else
polarvalue[i]=ans;
i++;
System.out.println(ans);
}
Hi, Friends this is my code and the swn.extracts a value which can be null so the ANS contains the null value and when i try to access it gives NULlPOinterException is there any way that i can check the NULL value and change it to any other value.? But if i removes the whole If..else section it gives no error and prints the "NULL" in the output...

If i remove the whole If..else section then the code prints the null
value.
If above is true, mean your polarvalue[] array is null and you are trying to assigned the ith position value by using polarvalue[i] that's way, it's throwing null pointer exception.
Do a null check of polarvalue[] array before assigned.
Your code is dangerous, It seems it can throw NPE every where like
while(i<word.length) // do a null check
ans=swn.extract(word[i], pos[i]); // do a null check
polarvalue[i]= " "; // do a null check
polarvalue[i]=ans; // do a null check
Do a null check it will take few minutes but reduce your most valuable time .

Related

Leaving the code in an else if() blank in order to escape the if statement

I'm sorry for the strange title, I couldn't find the exact wording that I wanted but I'll do my best to explain my question here. Basically I have some code that goes like this
if(both inputs are not null)
{
Do this
}
else if(both inputs are null)
{
}
else if(one input is null and the other isn't)
{
throw new Exception("Both inputs must have a value or neither should");
}
if I don't use the middle else if the last else if, the program will throw the exception no matter whether one or both inputs are null. I'm wanting it so that the program sees that both inputs are null and does nothing while continuing with it's execution. I'm using this data to pass to a SQl query and if one of the inputs are null it acts up. I might just be messing up the logic but I was wondering if this is considered bad practice. I can't think of a problem because there isn't a way that this could execute code accidentally. If there is a better way or if this is considered bad practice I would like to hear other ways to go about this. Thanks.
EDIT: clarified question
I think I'm missing something here. Your description doesn't seem to match your code.
In the pseudo-code you wrote, if both inputs are null, no exception should be sent, and that's what you want. But you are saying the exception is still sent ? Something is up here. Can you post something closer to your actual code ?
What you describe seems closer to the behavior of a switch case, where an empty "case" would just drop to the next one.
Both diregarding that, you can avoid those empty "else if" by re-ordering your tests :
if(both inputs are not null)
{
Do this
}
else if(one input is null and the other isn't)
{
throw new Exception("Both inputs must have a value or neither should");
}
This way, no need for an additional empty else if.
You can simplify the code if the language you are using has an Exclusive OR operator. For example in C#:
string A = null;
string B = "Hello World";
if ( A != null && B != null)
{
// Do this
}
else if ( A == null ^ B == null )
{
throw new Exception("Both inputs must have a value or neither should");
}
The result of x ^ y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true.
The easiest fix, in my opinion, would be to change your code to below
if(both inputs are not null)
{
Do this
}
else if((input1==null && input2!=null) || (input1!=null && input2==null))
{
throw new Exception("Both inputs must have a value or neither should");
}
Refactor out this logic in its own method, and then write it as following:
private void refactoredMethod(Input i1, Input i2) {
//Do nothing if both inputs are null.
if (i1 == null && i2 == null)
return;
//Throw if either of them is null.
if (input1 == null || input2 == null)
throw ...
//Neither input is null, do the normal processing.
//so, "Do this"
}
Why are you not checking if either one of the inputs is null?
Then you could throw an exception and continue afterwards if no exception was thrown.
So something like this (in java terms):
if(firstInput == null || secondInput == null) {
throw new IllegalArgumentException("Input must not be null");
}
// do what you want afterwards
How about this:
bool A = (input1 == null), B = (input2 == null);
if (A != B) {
throw new Exception("Both inputs must have a value or neither should");
}
I understand that source code is sometimes better readable with empty blocks for certain conditions. I assume this is what you want to do. Example:
if(street!=null && zip!=null)
{
storeAddress(street,zip);
}
else if(street==null && zip==null)
{
; // Do nothing
}
else // only one of street or zip was provided
{
throw new Exception("Street and zip code must be filled together or both left empty");
}
I use the semicolon here to avoid warnings from SpotBugs. This way I tell Spotbugs (and other developers), that the block is empty on purpose.
The last condition of your example is redundant, so I turned it into a comment.

How to get last object from arraylist in doChangeActivities?

Here is my code, i want to get last object from arraylist to get and set it for PrintActivity, can i?enter image description here
if(arrayList != null && !arrayList.isEmpty()){
arrayList.get(arrayList.size() - 1);
}

Java giving out of bounds exception when calling function twice?

I'm trying to find out if there is a variable that exists at some point in an ArrayList, but, when calling the function that does this, twice, I get an java.lang.IndexOutOfBoundsException. But when the function is called only once, it doesn't give an error, even though, when calling the function twice, they check to see if different indexes exist, not the same one.
Code;
//package mj.mjo.Vars;
public boolean varExists(int index){
return mjo_vars.get(index) != null;
}
Note, mjo here is a variable, with vars being another variable that is the mj.mjo.Vars class
//package mj.play.StudioCanvas;
int nonsys = mjo.vars.setVar("TEST", "LOLOLOL", false); // returns 1
int yessys = mjo.vars.setVar("SYSVARTEST", "WOOHO!", true); // returns 2
System.out.println("DOES THE VAR \"TEST\" EXIST? " + mjo.vars.varExists(nonsys));
System.out.println("DOES THE VAR \"TEST\" EXIST? " + mjo.vars.varExists(yessys));
The error indicates that the value of index that you pass to get() is greater than or is equal to the number of elements in the list. Change your code as follows to avoid the exception:
public boolean varExists(int index){
return index >= 0
&& index < mjo_vars.size()
&& mjo_vars.get(index) != null;
}
In general, the error means that something is wrong with your indexing scheme: list and array indexes in Java start at zero, and end at size()-1, inclusive. If passing 2 triggers the exception, but passing 1 is OK, then the list has only two elements - at indexes 0 and 1.

Getting error when checking combobox for null value

I got a combobox, and a submit button, when the button is submitted, i want to check if the combobox value was null. Im using this code:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem().equals(null)) {
infoLabel.setText("Combo box value was null");
}
i am getting this error when i press the submit button:
java.lang.NullPointerException
how can i fix this?
You can not call equals on null. Instead simply use == null.
Something like this:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
infoLabel.setText("Combo box value was null");
}
Should work.
You can not give the null reference to equals(), do it like this:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
infoLabel.setText("Combo box value was null");
}
And a remark that has nothing to do with your question: I suggest using the Java Naming Convention, which would lead to your combo box being named comboBox (and not ComboBox).
The condition should be :
ComboBox.getSelectedItem() != null
or
ComboBox.getSelectedItem().toString().equals("")
This checks if what is selected in the Combobox is null or empty
Another way of doing this is leaving the first item empty, then check for the selected index against 0 i.e
ComboBox.getSelectedIndex() != 0
Thanks

Ternary Operator and unexpected NullPointerException

I am getting NullPointerException from the below line sometimes.
System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
After adding brackets, it is fine.
System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
Please clarify me the behavior. Thanks in advance.
"Date::" + row is never null, although row sometimes is.
That is, "Date::"+ row != null is equivalent to ("Date::"+ row) != null which is always true.
It's a matter of operator precedence. Christoffer Hammarström has the executive summary. See this page http://bmanolov.free.fr/javaoperators.php for more detail.

Categories

Resources