I got a HttpResponse which gets a json response.
Now if the json response contains data it all works fine, but whenever the json is null my application crashes.
I've been trying to following code but with no avail.
(sb = json response)
Object result11 = sb;
Log.d("Result11", result11.toString());
if (result11 == JSONObject.NULL)
Log.d("if", "I am NULL");
else
Log.d("else", "I am not null");
I tried comparing result11 to:
null, "", "null", JSONObject.NULL
It always returns "I am not null"
Whilst the log says that Resul11 = null.
Any help would be appreciated. Thanks in advance.
EDIT:
Object result11 = sb;
Log.d("Result11", result11.toString());
StringBuilder test = (StringBuilder)result11;
if (test.toString().equals("null"))
Log.d("if", "I am NULL");
else
Log.d("else", "I am not null");
SOLUTION by #Mark Byers
test.toString().trim().equals("null")
results in "I AM NULL"
You don't have a null. You have a StringBuilder that when converted to a String contains the value "null".
To compare strings do not use the == operator. Instead you should convert to a String and use the equals method.
StringBuilder stringBuilder = (StringBuilder)result11;
String trimmed = stringBuilder.toString().trim();
if (trimmed.equals("null")) { ... }
The == operator compares the references and only returns true if the operands are references to the same object (or both null references). The equals method compares the values.
Related
Java String.equals versus ==
if you get a null result compare to a null pointer: result11 == null
Related
Is there any utility available to easily get the string representation of an arbitrary object if it exists and keep it null if it was null?
For example
String result = null;
if (object != null) {
result = object.toString();
}
but less verbose.
I have looked into ObjectUtils and String.valueOf but neither returns just null itself. Both return default strings, i.e. the empty string or the string "null" instead of just null.
If I understand your problem, you can use that (java.util.Objects is here since JDK7):
Objects.toString(s, null); // return null if s is null, s.toString() otherwise
In fact, it works for every object.
This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 4 years ago.
I got different simulation results when I programmed in these two ways:
if (S == null) {
return new LinkedList<>();
}
and
int len = S.length();
if(len == 0) return new LinkedList<>();
The first code gave me [""], which passed the testing. While the second one gave me [], got failed.
And I also noticed that there is another way: S.isEmpty()
Would anyone please explain? Many thanks!
String == null checks if the object is null (nothing, not even an empty string) and String#length() == 0 (actually, you should use String#isEmpty() instead) checks if the string object has 0 chars. Also, you can't access any methods if the object is null, it will throw a NullPointerException (or NPE for short).
difference between (string == null) and (string.length() == 0)?
Very different.
When you check (string == null), it checks whether the string reference is pointing to any existing object. If it is not referencing to any object, it will return true.
string.length() == 0 just checks your existing String object's content and see if its length is 0. If no object exist in the current variable when you invoke .length(), you get a NullPointerException.
S is a reference variable (you should write it in lower case).
S (or rather s) references an object that provides the method length().
You can only access the object referenced by s, if s is a really a reference to an object. If s is null (s==null), s does not reference an object and therefore, you can not call the method length(). If you try, you will get a NullPointerException.
When s references an object, you can call the length method on that object. In this case, it is a string object. A string object may exist without any characters (empty string, or "").
String s; // just a reference, initial value is null
s = ""; // s now references an empty string and is no longer null
new String(""); // create a new object with an empty string
In Java, you never really work with objects. You only work with references to objects, though in most cases, it appears as if you work with the object directly.
Keep in mind that the reference variable and the object are really to different things.
If the string you are passing into the second one is null, an exception should occur, since .length() will throw an exception when called on a null string.
if a String instance is null, myInstance.length() == 0 would throw a NullPointerException, because you call an instance member of a not instantiated instance and crash your application.
So, if you're not sure your String instance is instantiated, always do a null-check, or better yet, with Java 8 or later, use Optional to avoid null's.
S == null mean that there if you try to print something for instance, nothing wiil happen (or maybe a nullPointerEcxeption) because null mean that there is nothing inside this variable.
String.lenght(S) == 0 mean that your string equals to ''
for instance :
String S1 = '';
String S2 = null;
try{
System.out.println(S1.length() == 0) {
System.out.println('S1 is not null');
}catch(nullPointerExeption e){
System.out.println('S1 is null');
}
try{
System.out.println(S2.length())//it will throw you a java.nullpointerexcption
System.out.println('S2 is not null');
}catch(nullPointerExeption e){
System.out.println('S2 is null');
}
The system will write
0
S1 is not null
S2 is null
//case1
String s;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
//error: variable s might not have been initialized
//case2
String s=null;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
/* output
I am null
error: Null pointer exception
*/
//case 3
String s=new String();
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
String s="";
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
if a HashMap is empty and I check for .containsKey()
I get a null answer.
My Problem is that If I want to check for null I get an error message
if(containsKey == null || !containsKey){
I receive the error message
Operator '==' cannot be applied to 'boolean', 'null'
Can someone tell me why this is happening. I thought that this should work
Check that the map isn't null (not that HashMap.containsKey(T) returned null, because it didn't - it can't. It returns a boolean primitive, which can only be true or false).
if (map != null && map.containsKey(someKey)) {
// ...
}
You can use the HashMap .isEmpty() method to check if your hashmap is empty or not.
containsKey can't be null as it is the method being called. Try checking if the map itself is null.
Booleans are primitives, and primitives will never be null.
Only Object classes can be null.
Following this argument, you can do this for object class Integer:
Integer myObject = 1;
if (myObject != null){
...
}
But you cannot do this for int, which is a primitive like booleans:
int myPrimitve = 1;
if (myPrimitve == null){
...
}
Your IDE will show the error Operator == cannot be applied to int, null
I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.
How do we compare null values ?
For example, I am trying to compare null by
class_name == "null"
But the code doesn't checks if the class is null.
What's wrong ?
You are comparing it to the reference of the String "null".
Remove the double quotes so you get the special null type (JLS).
You want:
class_name == null
↑
class_name == null because in your way you compare it to string not to null
if(class_name == null)
// do something;