null pointer exception in writing file in java - 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
}

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.

How do you break a nested method calling in different objects?

The situation is as follwing
student.studentsPhone.studentsAccount.topUp(xxx)
student is an object that has the method studentsPhone which returns the a variable of type Phone and the phone object has a method studentsAccount which returns the a variable of type Account that finally has the required method.
So my question is if I have a student object and no phone, I will get a null pointer exception. Is there a way to cut the line where we wanted?
bare in mind that I don't want to instantiate everything in the main class. I will just instantiate the Student class.
I though of several approaches
Move the method up the heirarchy, but the other objects won't be of any use really
in the studentsPhone method I say if (Phone == null) return; but its not void and there are other methods after studentPhone
You can use ternary operator for this, something like:
String result = student != null ? (student.studentPhone != null ? (student.studentPhone.studentsAccount != null ? student.studentPhone.studentsAccount.topUp(xxx) :"return"): "return") : "return"
or like:
boolean isNotNull = student != null ? (student.studentPhone != null ? (student.studentPhone.studentsAccount != null ? true : false): false) : false;
if(isNotNull){
student.studentPhone.studentsAccount.topUp(xxx);
}
You could throw your own type of runtime exception if there is no phone. Wrap your code in a try/catch block, catching your own exception and then carry on with the rest of your function
void doSomeThing() {
Phone getStudentPhone() {
if(phone == null) {
throw new noPhoneException();
}
return phone;
}
}
try {
student.getStudentPhone().studentsAccount.topUp(xxx);
} catch(noPhoneException e) {
// say something about no phone existing
}

Weird nullpointer exception

I have this method in my superclass, which extends activity:
protected boolean isStopAvailable(BusStop stop) {
if (stop == null) {
stop = new BusStop();
} else if (stop.getName().length() > 0) {
return true;
} else {
return false;
}
return false;
}
I call it in my subclass isStopAvailable(object); How is it even possible to get a null pointer exception while using a method from the object after I've initiated the object?
stop.getName() returns null
else if (stop.getName() != null && stop.getName().length() > 0)
should solve it
If getName() returns null, you will get a NPE. You are trying to do a length function on a null object, hence this exception. You should add another else if check:
...
else if (stop.getName() == null) {
// do something
}
Hope this helps.
I would bet that the name field in stop is null. Your first check is to see if the object is null, not the fields inside of it. Thus, if stop.getName() returns null, you get an NPE when attempting to invoke the length
I suggest that the NPE is thrown in this line: else if (stop.getName().length() > 0)
Thats possible because you've checked if the object BusStop is null but you didn't checked if stop.getName() could be null.
Do something like that:
else if (stop.getName() == null) {
// set stop.setName()
}
Hope this helped, Have Fun!
stop.getName() is returning null ,that is why you are getting NPE.

Variable can only be null shows eclipse

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 ;)

Null pointer exception double

Can somebody explain me why I am getting a NullPointerException here:
String s = request.getParameter("tbExample");
_tbExample = new Double (Double.valueOf(s).doubleValue());
s may be null. According to javadoc, if s is null, valueOf will throw a null pointer exception.
Try checking s for null before continuing.
Probably the tbExample parameter does not exist in your request.
Therefore null is being returned to indicate that fact, and is being assigned to s. This is then passed to Double.valueOf, which is invalid input.
Try something like this:
String s = request.getParameter("tbExample");
if(s == null)
{
// Handle the error.
// You could log something, throw exception, exit early, etc.
// Do whatever is appropriate for your application.
}
else
{
_tbExample = new Double (Double.valueOf(s).doubleValue());
}
I can see why you are confused here. You are taking a String, parsing it into a Double, turning it into a double and back into a Double again. A much simpler solution is to do
_tbExample = s == null ? null : Double.valueOf(s);
This handles the situation where s is null and turns a String into a Double
Here is a simple test program for you.
Double _tbExample;
String s = null;
_tbExample = s == null ? null : Double.valueOf(s);
System.out.println("_tbExample="+_tbExample);
prints
_tbExample=null

Categories