I know it's not possible to call the equals method on a null object like that:
//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2))
{
System.out.println("NOT WORKING :'(");
}
But in my case I want to compare two objects from two database and these two objects can have attributes null...
So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.
This method is good or not ?
//WORKING
String s1 = "test";
String s2 = "test";
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}
//WORKING
String s1 = null;
String s2 = null;
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}
I'm not sure because in this case it's not working ... :
//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2)|| s1 == s2 )
{
System.out.println("NOT WORKING :'''(");
}
You will need to check atleast one is not null before doing equals method -
here
s1==s2
will work incase ofnull==null
. But if even one is not null, then you need to check atleast s1 before doing equals.Update: As edited by @'bernard paulus', if you are using Java 7, you can use java.util.Objects.equals(Object, Object)
I think you are comparing two objects.
So it should be like this
True - for equal False - for not equal
If you want to know if something is 'null' you can compare using:
If it is null it will tell you true. Problem, if you have a String that is null, you can't use the methods equals(). For this reason your third part doesn't work, because if it is equals you can't use a null pointer.
You should check first if the object is null and then if it isn't null use the methods equals.
On the other hand be careful because maybe you want to compare the empty String, in this case you have to use equal(""). If you want to compare the empty string, is better that you put first the empty string on this way:
Sorry for my English I hope it helps you.