Variable can only be null shows eclipse - java

I have wriiten a method like this
public ArrayList<T> GetDoctorDetail(String name)
{
if (name!=null || !name.isEmpty() || name!="")
{
//Statements
}
}
but in eclipse !name by underline with a yellow line show
Null pointer access: The variable name can only be null at this location.
why? and what is the solution.

If name is non-null, the conditional || operator won't evaluate the second operand at all. So the only case in which the second operand can be evaluated is when name is null, in which case it will throw.
I suspect you want
if (name != null && !name.isEmpty())
{
// Use name
}
Or possibly:
if (name == null || name.isEmpty())
{
// Show an error message
}
Note that comparing strings with == and != is also almost always the wrong thing to do, as it compares references. You would normally use equals instead. Not only that, but it would be useless anyway here - it could only be equal to "" if it's empty, so it's the exact same condition as the second operand.

The first part of the oR condition will only fail if name = null. Hence the second part will throw a null pointer exception.
The correct way to write that condition is
if (name!=null && (!name.isEmpty() || name!=""))

if (name != null && !name.isEmpty()) {
// Now the name variable has valid content
}
Note - The logic is always much easier to understand if you create "positive" checks:
if (name == null || name.isEmpty()) {
// Now name is either null or empty
} else {
// Now the name has valid content
}
Try to avoid conditions that check for "negative" states, like "is not null" and "is not empty". They're nothing but brain twisters ;)

Related

Why null check is necessary in the below code?

public boolean isValidCardDetails(CardDetailsTypeBean cardDetailsTypeBean) throws EnrollmentReqInvalidException {
if (cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())) {
throw new EnrollmentReqInvalidException("ECDOO16", "card no is mandatory");
}
if (cardDetailsTypeBean.getNameOnCard() == null || "".equals(cardDetailsTypeBean.getNameOnCard())) {
throw new EnrollmentReqInvalidException("ECDOO17", "name on card is mandatory");
}
if (cardDetailsTypeBean.getCvv() == 0 || "".equals(String.valueOf(cardDetailsTypeBean.getCvv()))) {
throw new EnrollmentReqInvalidException("ECDOO18", "cvv is mandatory");
}
if (cardDetailsTypeBean.getExpDate() == null || "".equals(cardDetailsTypeBean.getExpDate())) {
throw new EnrollmentReqInvalidException("ECDOO19", "exp date must be required");
}
return false;
}
Well here i want to ask after getting card number and checking null,why we use "".equals there..?? can anyone explain me this? little confused?
This line of code:
cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())
simply verifies if cardNumber is null or if is equal to the empty string. Empty string is different from null value, so this code checks if every field read by a getter returns a non-empty, non-null value.
It's superfluous, actually.
The reason for this is that the order of the equals statement on the other side of the logical comparison is guaranteed not to produce a NullPointerException, since String.equals(null) is engineered to produce false.
The reason it likely exists the way it does is that it's being made explicit that the code is checking for null and an empty string.
"" isn't the same as null because "" is a String value. Your card number might instantiated with ""
null means the reference of card number has no value.

Java NullPointerException in if statement

I currently get the NullPointerException in my following code.
else if (isEmpty(href))
System.err.println("This is an empty link: " + href);
Where the isEmpty function is the following.
public boolean isEmpty(String HREF){
if (HREF.equals("") || HREF.equals("null") || HREF == null || HREF.isEmpty())
return true;
else
return false;
}
Is it because I can not compare a string to null? What can I do to make this function work?
Your isEmpty test is just doing things in the wrong order. Change this:
if (HREF.equals("") || HREF.equals("null") || HREF == null || HREF.isEmpty())
return true;
to:
if (HREF == null || HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
If HREF is actually null, then the first test will short-circuit the rest of the if and you won't get a NPE.
(By the way, explicitly testing HREF.equals("") and also calling HREF.isEmpty() is redundant. You only need to do one or the other.)
By the by-the-way, I would recommend, as a matter of style simplifying your method to a single return statement:
public boolean isEmpty(String HREF){
return HREF == null || HREF.isEmpty()) || HREF.equals("null");
}
(Also, if testing against the string "null" was an attempt to check against a null value, you can drop that condition as well. In fact, you could then use something like Apache Commons' StringUtils.isEmpty(CharSequence) method to do what you want.)
changing the order in your if will solve it.
public boolean isEmpty(String HREF) {
return HREF == null || HREF.equals("") || HREF.equals("null") || HREF.isEmpty();
}
this way, when HREF == null, none of the other tests will be evaluated.
When HREF is null , referencing it with dot operator will throw a null pointer exception .
Different ways to solve this is as follows
public boolean isEmpty(String HREF){
if (HREF == null ||HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
else
return false;
}
this is by just re arranging your conditions, by short cut of boolean operations, this will avoid referencing a null pointer in subsequent checks.
OR
public boolean isEmpty(String HREF){
//handling null case first of all
if(HREF == null) return true;
if(HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
else
return false;
}
Also avoid redundant use of checks like HREF.equals("") and HREF.isEmpty() are similar.
Another best practice to check equals with a string object is to use the constant in the beginning as in "".equals(HREF) and "null".equals(HREF), here we are pretty sure that "null" is a valid string and which is not null
You cannot call methods of the null here HREF.equals("")
Common practice is to change the order "".equals(HREF) . This is null safe. And you will not need HREF.isEmpty() part this way.
So the code will become
public boolean isEmpty(String HREF){
return HREF == null || "".equals(HREF) || "null".equals(HREF);
}
I have removed the unnecessary if here as we are returning the result of boolean expression.
If HREF is null, then doing this:
HREF.equals("")
will throw a NPE.
Do the null check first:
HREF != null && /* rest of conditions */

null pointer exception in writing file in java

I am facing an exception while writing to the file. i am giving the code below.
private static void readCsvFromFileAmazon(List<String> filelist)
throws BiffException, IOException,NullPointerException {
FileWriter fw = new FileWriter("total_number_of_products_amazon.txt", true);
String numberOfProducts = getProductNumber(url);
System.out.println(category);
System.out.println("##############" + numberOfProducts);
// call function to get the number of products. \
if (!numberOfProducts.equals(null) || !numberOfProducts.equals(" "))
{
fw.write(numberOfProducts);
}
else
{
System.out.println("cant write null product");
}
fw.close();
}
the value getting in number of products is null then exception happening
Exception in thread "main"
##############null
java.lang.NullPointerException
exception happening in this line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
You must check numberOfProducts content in different way:
if(null != numberOfProducts ||!"".equals(numberOfProducts))
instead of if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
because if numberOfProducts is null, then invoke a method equals on null object throws a nullPointerException.
Hope this helps,
in your if statement numberOfProducts.equals(null)
you are comparing a string to a null string. this doesnt have any effect since you are comparing a null object.
remember that String is an object and you need to check object if they are null in this kind of way numberOfProducts == null or numberOfProducts != null
You cannot check if null.equals(null) - it throws an exception, NullPointerException, for tying to access the equals() method of null. First, make sure numberOfProducts is not null itself, using the == operator:
if (numberOfProducts == null) {
//do something
} else {
...
}
Also note that the line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
Makes no sense logically. Assuming null.equals(null) would work (IT DOES NOT), The second (right) operand - !numberOfProducts.equals(" "), will be evaluated only if numberOfProducts == null, so whenever the right operand is evaluated - it will always yield false.
This means your condition could be shortened to simply:
if (numberOfProducts != null)
As you posted for:
System.out.println("##############"+numberOfProducts);
Output is:
##############null
This means numberOfProducts is null hence if you attempt to call any non-static method on it like this:
numberOfProducts.equals(null)
will throw a NullPointerException. If you want to check if it's null, do it like this
if (numberOfProducts != null && !numberOfProducts.equals(" ")) {
fw.write(numberOfProducts);
}
I think this will work
if(numberOfProducts!=null && !numberOfProducts.rquals(" ")){
//doSomething
}else{
//doSomethingElse
}

Java boolean precedence comparation with ternary operator

I'd found a nice situation that I don't understand at all related to Java boolean operator precedence. I know and verify with the oracle official documentation here that && and || have precedence against ternary operator ? :
Now I have a weird line in my code similar to that
if (a.getItem() != null && a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue())
{
......
}
What I get, well, a nice java.lang.NullPointerException at a.getItem().getOtherItem() becouse a.getItem() is null. How I can solve it, encapsulate it between parenthesis
if (a.getItem() != null && (a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue()))
{
......
}
So my question is why I get a NullPointerException if I follow the Oficial Documentation previously linked && has precedence against ?: and && is short circuit evaluated (answered also here in some questions).
It seems you are confused about what “higher precedence” means. Let’s explain with a simple example:
The operator * has higher precedence than the operator '+'. This means that the expression a*b+c is evaluated like (a*b)+c. The same applies to the && operator and the ternary operator:
&& has higher precedence than the operator ? :. This means that the expression a&&b?c:d is evaluated as (a&&b)?c:d.
Hence the operator precedence works as documented in your example. It does exactly what you requested:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
true:a.getItem().getOtherItem().getSomevalue())
If a.getItem() is not null and a.getItem().getOtherItem() is not null evaluate to true, otherwise to a.getItem().getOtherItem().getSomevalue(). So when either of the values is null, the code will attempt to evaluate the third term which will yield to a NullPointerException.
It’s not clear what you actually want to achieve. In your second example you say:
if (a.getItem() != null && (a.getItem().getOtherItem() != null?
true: a.getItem().getOtherItem().getSomevalue()))
so you want to interpret the case when a.getItem() is null as false but in the braced term you request to interpret the case when a.getItem().getOtherItem() is not null as true while the case that a.getItem().getOtherItem() is null should cause getSomevalue() to be called on the reference that you just have proven to be null.
What you most likely want to do is to evaluate a.getItem().getOtherItem().getSomevalue() if the all values are not null:
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): false)
Note that you can express the same without the ternary operator at all. The equivalent statement would be:
if (a.getItem() != null && a.getItem().getOtherItem() != null
&& a.getItem().getOtherItem().getSomevalue())
In the case the fall-back value ought to be true like in
if (a.getItem() != null && a.getItem().getOtherItem() != null?
a.getItem().getOtherItem().getSomevalue(): true)
the same can be expressed as
if (a.getItem() == null || a.getItem().getOtherItem() == null
|| a.getItem().getOtherItem().getSomevalue())
Whenever you see true or false in a compound boolean expression you can be sure that there is something wrong.
The general use case for ? is to replace an if in a simple assignment branch, something like:
int a;
if(isOdd(b) || isPrime(b))
{
a = b;
}
else
{
a = -b;
}
into simply
int a = isOdd(b) || isPrime(b) ? b : -b;
And for this use case, it makes sense that && and || have precedence over ?.
The confusion arises only if ? returns boolean, the way you use it inside an if, which in my experience is very rare.
iI'd say that in your if statement
if (a.getItem() != null && a.getItem().getOtherItem() != null?true:a.getItem().getOtherItem().getSomevalue())
the following most inner part must be evaluated first
null?true:a.getItem().getOtherItem().getSomevalue()
so that the following part can be put together
if (a.getItem() != nulla.getItem().getOtherItem() !=<result_from_most_inner_part>)
In any case this if statement is ugly. Make the code rather readable and the compiler will do its part :P

using method that take variable number of parameters

I am trying to make a method that build new object of the class (PhoneBook) using different constructors according to the number of parameters ,, but it gives an error
( Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 )
public static PhoneBook createObjects(String fName,String lName,String num,String...optional)
{
n++;
if (optional[0]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num);
else if (optional[1]==null)
ArrayOfObjects[n]=new PhoneBook(fName,lName,num,optional[0]);
return ArrayOfObjects[n];
}
Instead of checking whether optional[0] == null, you should examine optional.length to determine if the optional parameter is present.
The same goes for optional[1].
Rather than checking optional[0] and optional[1] here, you should check to optional.length. Also, keep in mind that optional itself may well be null, so something like:
if(optional != null) {
if(optional.length > 0) {
// I now know that optional has at least one element in it, and optional[0] should be valid, though I don't know that it is non-null.
if(optional.length > 1) {
// I now know that optional[1] is valid, though I do not know it is non-null.
}
}
}
if you NEED non-null:
if(optional.length > 0 && optional[0] != null)
The second part, optional[0] != null will only be called if the first evaluates to true.

Categories