Ternary Operator and unexpected NullPointerException - java

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.

Related

Conditional for insert into - Java

I need to create a condition to insert or not the data in a table.
There are 11 fields and from 6 to 11 the user may or may not fill it out. If not, It can't save any data in this table. The condition, if the field is white, null or empty, was create, but the insert is being made . Does anyone know how to fix? Thank you!
ps. When one of the information is not filled in by the user, the insert should not be made
try {
PreparedStatement ps_SOFVDISN = connection.prepareStatement(SQL_INSERT_SOFVDISN);
for (BeanItem beanItem : beanItemLista) {
ps_SOFVDISN.setString(1, beanItem.getChaveSolicitacao().getCodEstb());
ps_SOFVDISN.setString(2, beanItem.getChaveSolicitacao().getCodPedi());
ps_SOFVDISN.setString(3, beanItem.getChaveSolicitacao().getNumSolcServ());
ps_SOFVDISN.setString(4, beanItem.getItemSs().getNumItemSs()); // NUM_ITEM
ps_SOFVDISN.setString(5, " ");
ps_SOFVDISN.setString(6, beanItem.getNotaFiscalRef().getSerNfRef());
ps_SOFVDISN.setString(7, beanItem.getNotaFiscalRef().getNumNfRef());
ps_SOFVDISN.setString(8, "");
ps_SOFVDISN.setString(9, "");
ps_SOFVDISN.setString(10, beanItem.getNotaFiscalRef().getCgcEstbRef());
ps_SOFVDISN.setString(11, beanItem.getNotaFiscalRef().getQtdUsadaReferencia());
if (beanItem.getNotaFiscalRef().getSerNfRef() != null && !beanItem.getNotaFiscalRef().getSerNfRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getNumNfRef() != null && !beanItem.getNotaFiscalRef().getNumNfRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getCgcEstbRef() != null && !beanItem.getNotaFiscalRef().getCgcEstbRef().trim().equals("")
|| beanItem.getNotaFiscalRef().getQtdUsadaReferencia() != null &&
!beanItem.getNotaFiscalRef().getQtdUsadaReferencia().trim().equals("") && !beanItem.getNotaFiscalRef().getQtdUsadaReferencia().equals(" "))
{
if (ps_SOFVDISN.executeUpdate() == 1) {
System.out.println("Sucess - Insert ok");
retornoResult = true;
}
}
and what about adding not null constraint in database for columns, which user must define?
Outside of adding null constraints, you can use the ternary operator to check if those fields are null or empty before setting them.
ps_SOFVDISN.setString(6, !beanItem.getNotaFiscalRef().getSerNfRef().isEmpty() ? beanItem.getNotaFiscalRef().getSerNfRef() : "");
Look into either DB Constraints or Java bean validation frameworks. You want to validate your data before allowing it into your DB.
Generally, I would recommend one of these 3 options in this order to handle your validation:
Use the DB Constraints (Easy to do, Guaranteed, Good for many simple use cases)
Use a framework (Good for complex use cases)
Write validation yourself to kick out before INSERT
There are more pros and cons to each approach, but too much to get into here.

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.

Why is the conditional (ternary) operator evaluated in a logical AND when the lhs is false

return super.isAvailable() && expander != null
&& rightNotLeft ? !expander.isExpandedRight() : expander.isExpandedRight();
My problem was that when expander was null I was getting a null pointer exception. But I didn't think that this should happen since expander!=null is being evaluated to false and since ANDs are being used the entire expression should short circuit and return false.
return super.isAvailable() && expander != null
&& (rightNotLeft ? !expander.isExpandedRight() : expander.isExpandedRight());
The above code (adding the parentheses) solved the problem. However this does not make sense to me as no matter what happens in the conditional operator there is no way to return true so shouldn't it short circuit?
Thank you for your responses.
This is due to operator precedence. Your condition without explicit parentheses is actually evaluated like
return (super.isAvailable() && expander != null
&& rightNotLeft) ? !expander.isExpandedRight() : expander.isExpandedRight();

How to access NULL value

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 .

In Java, what are the boolean "order of operations"?

Let's take a simple example of an object Cat. I want to be sure the "not null" cat is either orange or grey.
if(cat != null && cat.getColor() == "orange" || cat.getColor() == "grey") {
//do stuff
}
I believe AND comes first, then the OR. I'm kinda fuzzy though, so here are my questions:
Can someone walk me through this statement so I'm sure I get what happens?
Also, what happens if I add parentheses; does that change the order of operations?
Will my order of operations change from language to language?
The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&, then ||. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.
It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.
Boolean order of operations (in all languages I believe):
parens
NOT
AND
OR
So your logic above is equivalent to:
(cat != null && cat.getColor() == "orange") || cat.getColor() == "grey"
The expression is basically identical to:
if ( (cat != null && cat.getColor() == "orange") || cat.getColor() == "grey") {
...
}
The order of precedence here is that AND (&&) has higher precedence than OR (||).
You should also know that using == to test for String equality will sometimes work in Java but it is not how you should do it. You should do:
if (cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
...
}
ie use the equals() methods for String comparison, not == which simply does reference equality. Reference equality for strings can be misleading. For example:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
First, your if statement contains three main expressions:
cat != null
cat.getColor() == "orange"
cat.getColor() == "grey"
The first expression simply checks whether cat is not null. Its necessary otherwise the the second expression will get executed and will result in a NPE(null pointer excpetion). That's why the use of && between the first and second expression. When you use &&, if the first expression evaluates to false the second expression is never executed.
Finally you check whether the cat's color is grey.
Finally note that your if statement is
still wrong because if cat is
null, the third expression is still
executed and hence you get a null
pointer exception.
The right way of doing it is:
if(cat != null && (cat.getColor() == "orange" || cat.getColor() == "grey")) {
//do stuff
}
Check the order of parenthesis.
Yeah && is definitely evaluated before ||. But I see you are doing cat.getColor() == "orange" which might give you unexpected result. You may want to this instead :
if(cat != null && ("orange".equals(cat.getColor()) || "grey".equals(cat.getColor()))) {
//do stuff
}
Order of Operation is not what you need, you need boolean algebra, this includes boolean functions. Maxterms/minterms, Gray code, Karnaugh tables, diodes,transistors, logic gates, multiplexers, bitadders, flip flops...
What you want is to implement boolean "logic" on computers or virtual machines. With "order of operations" you may refer something about physics like managing delays on logic gates (OR, if) nanoseconds intervals?

Categories

Resources