Why I am getting NullPointerException in my ternary operator? - java

My ternary operator is throwing a NullPointerException even though I explicitly check if the value of my list is null. However, if I add parenthesis around the ternary operator, my code works.
Code without parenthesis (throwing the exception):
final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " +
listData != null ? listData.size() : 0);
Code with parenthesis (working fine):
final List<String> listData = null;
System.out.println("Insert new data (Created Monitorings) : " +
(listData != null ? listData.size() : 0));
Can somebody explain it how exactly it is working.

This is about precedence of operators: the String+ has a much higher precedence than following ternary operator.
Therefore your first snippet actually does this:
( "Insert new data (Created Monitorings) : " + listData ) != null
? listData.size() : 0
Meaning: you concat a string (with a null listData), and compare that against null. Obviously that concat'ed string isn't null. Thus you do call listData.size(). And that resembles to null.size() which leads to your NullPointerException.
You are comparing the wrong thing against null! In the second snippet the ( parenthesises ) ensure that the result of ternary operation gets added to your string.

in snippet one the value that is compared to null is "Insert new data (Created Monitorings) : " + listData

'+' has more precedence than '!='
Hence Snippet 1 translates to:
(("Insert new data (Created Monitorings) : " + listData) != null ? listData.size() : 0;
The expression is not null so it proceeds to listData.size(). But as it is null, it throws the exception.

Related

Hashmap get() method returns null but when comparing with null prints false

There is a hashmap
HashMap<String,ArrayList<String>> hm = new HashMap<>();
It has these values
entertain - have,
some - one,
very - extremely, actually, really, super,
auto - car,
lunch - meal,
wagon - car,
truck - car,
Problem statement
System.out.println("test " + hm.get("delicious")); //prints null
System.out.println("test " + hm.get("delicious") == null); //prints false
why is the second print statement printing false, should it not print true?
The expression passed to the println method is evaluated from left to right. First the String "test " is concatenated to hm.get("delicious"), and only then the output is compared to null.
Therefore:
System.out.println("test " + hm.get("delicious") == null);
is equivalent to:
System.out.println(("test " + hm.get("delicious")) == null);
"test " +hm.get("delicious") is definitely not null (it's actually equal to the String "test null"), so false is printed.
System.out.println("test " + (hm.get("delicious")==null));
will print "test true".
Before we try to find a solution to this question, we should understand that what exactly is null in memory? Or What is the null value in Java?
First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.
Let's come to the actual question. the following code is internally used by java to compare.
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
I hope, now you can understand why your program says false.

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
}

Retrieving the null value from Sqlite database in android

Guys i have stored a null value in the column of sqlite database
the value that is storing is return "null"
Now using following code to retrieve it
int i = resultSet.getInt(resultSet.getColumnIndex(columnName));
String str = resultSet.getString(resultSet.getColumnIndex(columnName));
boolean bool = resultSet.isNull(resultSet.getColumnIndex(columnName));
if( str == null ) {
return -1;
}
return i;
The debugger shows the value of str = "null"
but this condition is not working with str == null , str == "" , str == "null"
anyone can give me a hit of what to do..
Also resultset.isNull gives me a value of false.
So how can i store null in database, secondly if i use "null" then how can i make this condition work.
If you have stored the "null" literal string in the database, you compare against it like so --
if ( "null".equals(str) )
To store a null value in your database table, you use PreparedStatement.setNull()
Also resultset.isNull gives me a value of false.
resultset.isNull will give true if your your value = null. But as you said your value = "null" , which is a String.
The debugger shows the value of str = "null"
but this condition is not working with str == null , str == "" , str == "null"
try comparing with str.equals("null")
mDb.execSQL(updateQuery, valVars); USING this and null as one of the arguments stored in valVar but it gives error of null pointer exception
As sepcified on http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html this method should be used to - Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
Please try using update(String table, ContentValues values, String whereClause, String[] whereArgs) or updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm). Also please cross verify that your field in db allows NULL(i.e. Not Null = 0)
hope this helps :)
Check for String length.like,
if(str.length == 0){
}

Strange Null pointer exception case: ternary conditional operator not working with string concatenation

StringBuffer sb=null;
// Some more logic that conditionally assigns value to the StringBuffer
// Prints Value=null
System.out.println("Value="+sb);
// Throws NullPointerException
System.out.println("Value=" + sb != null ? sb.toString() : "Null");
The fix for this issue is encompassing the ternary operator in brackets:
// Works fine
System.out.println("Value=" + (sb != null ? sb.toString() : "Null"));
How is this possible?
A + has a higher precedence than a !=.
So you evalutate "(Value="+sb ) != null at first.
Let's bracket the expression the way that the compiler effectively would, in the broken vase:
System.out.println( ("Value" + sb != null) ? sb.toString() : "Null");
Now "Value" + sb will never be null even if sb is null... so when sb is null, it's calling toString() and going bang.
I think the issue is that the statement is being parsed like this:
System.out.println( ("Value="+sb) != null ? sb.toString() : "Null" );
The string concatenation operator (+) has a heigher precedence than the ternary operator.
Since "Value"+null is always not null, sb.toString() will always be called, even if sb is null, hence the NullPointerException.
If in doubt - parenthesize! Even if not in doubt! :)
The ternary operation bypasses the toString method on the null object, which is what is causing the NullPointerException.
the exception is cause when sb.toString() gets executed.
In the fix you check if sb is null before executing so the offending call is not attempted.
System.out.print() is implemented like that:
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
With sb = null, sb.toString() means null.toString() which leads to you NullPointerException

Double != null is causing a NullPointerException

I have the following snippet of code that is causing me bother, where currentRate and secondCurrentRate are Double objects, correctly defined:
(currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
This should check each each Double for null-ness and assign the value null accordingly. However, if secondCurrentRate is null, this causes a NullPointerException.
I have changed the snippet to this:
(currentRate == null | secondCurrentRate == null) ? null : currentRate * secondCurrentRate;
And this works as expected. My question is why is this happening? I could understand it if I was calling some method on the objects but my understanding was that NullPointerExceptions were thrown when a method was called on a null object. There is a null object but there is no method call.
Can anyone offer any insight into this? This is running in Java 5.
I think your problem is elsewhere.
This works :
Double currentRate=null, secondCurrentRate =null;
Double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
But if you've done this, it will cause a NPE:
Double currentRate=null, secondCurrentRate =null;
double test = (currentRate != null && secondCurrentRate != null) ? currentRate * secondCurrentRate : null;
The type of the conditional operator is actually quite complicated. I believe what happens in your first example, is this: The second operand of the conditional,
currentRate * secondCurrentRate
is of type double, and this also becomes the type of the entire expression. Then, when either of the values are null, it tries to set the value of the expression to the Double null, which is unboxed into a double and causes a NPE.
The reason the second expression works is due to slightly different semantics of the conditional expression in this case.

Categories