I am having difficultie while validating a long variable if it is null.
The Code which I am using is :
long late_in= latein_hours.getTime();
It will show an error that java null pointer exception. So how can I validate if it is null then make it equal to zero.
Thanks
long late_in = 0;
if(latein_hours!=null){
late_in= latein_hours.getTime();
}
Primitive can't be null, only reference to object can hold null value
A long can’t be null: if you don't set a value, is automatically set to 0.
If you want a variable that can be null (for example if not initialized), you must use Long (look the case).
Long is like a container for long that can be null.
Long latein_hours;
long late_in;
if(latein_hours!=null){
late_in= latein_hours.getTime();
}
The long isn't null. latein_hours is.
If this is intentional, then you can do:
long late_in = latein_hours == null ? 0 : latein_hours.getTime();
I'm not sure if latein_hours is null or if getTime() returns a Long which is null. Either way you just need to check for the null like this:
long late_in = 0;
if (latein_hours != null && latein_hours.getTime() != null) {
late_in = latein_hours.getTime(); //auto unboxing
}
else {
// was null
}
It's the second case which often trips people up when using autounboxing, you do get some null pointer exceptions in code you thought of as just doing some maths with primitives.
if(latein_hours!=null) {
long late_in= latein_hours.getTime();
}
You will get a null pointer exception, if you invoke anything on the null object. i.e
if
latein_hours = null;
latein_hours.getTime(); // NullPointerException
Related
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.
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
}
I am checking for null before doing a certain operation but I have run into some issues. Following is the code:
if (c != null && c.size() != null) {
if (c.size() > 0) {
return (Application) c.toArray()[0];
}
I am getting a 'The operator != is undefined for the argument type(s)int, null' at the point
c.size() != null. I understand the return type for the size method is an integer, is that why I am getting this error? Hope someone can advise. Thank you.
int is a primitive type and is not an Object so is not a reference that can be null. Read more in this previous answer
Then in your code just remove that condition.
And also is preferred you use c.isEmpty() rather than c.size()>0
Your code would look like this:
if (c != null && !c.isEmpty()) {
return (Application) c.toArray()[0];
}
First of all, the result of c.size() is an integer. An int is a primitive, and it cannot be null. Only objects can be null.
Second, c.size() will never return null, so the check
c.size() != null
is unnecessary.
Note: There are wrapper classes for each primitive type. For example
Integer i = 4;
i = null; // valid
That assignment will be valid because i is an instance of the class Integer.
We have a nullable (type long) column (named referral) in our MySQL database. We use hibernate for ORM.
I am trying to get the value of the column for a given member. Some are null, and if its not, its an id that points to another member whose is the referrer.
The problem is in the java code I am trying to detect if that member's column is null, if not, do something.
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
member.getReferral() returns the value (type long) of the referral column. Some of those columns are null and some are not.
The above code compiles fine, but I get a nullPointerException when I call the method on a user whose referral column is null.
How do I properly do a detection on this?
Thanks in advance!
Full Answer:
Thanks to #Marcelo for the best correct answer.
Here is the code in its final state:
Long referrerAffiliateId = member.getReferral();
if (referrerAffiliateId != null) {
//...
}
Assuming member.getReferral() returns a Long, use:
if (member.getReferral() != null)
In Hibernate, if you want to be able to detect nullability in a property, you must not use primitive types, because they will always have a default value 0 for longs.
The exception probably comes from Long.toString(), try checking the value before converting to a string:
Long ref = member.getReferral();
if (ref == null) {
// Do something...
} else {
String referrerAffiliateId = Long.toString(ref);
// ...
}
Change
String referrerAffiliateId = Long.toString(member.getReferral());
if (referrerAffiliateId != null){
//do something
}
To:
if (member.getReferral() != null){
String referrerAffiliateId = Long.toString(member.getReferral());
//do something
}
It's likely that you're getting the NullPointerException when you call Long.toString() with a null parameter.
use Below code:
Long ref = member.getReferral();
String referrerAffiliateId = null;
if(ref != null){
referrerAffiliateId = Long.toString(ref);
}
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