Reputation: 1539
I want to do something like below in java.
String subject=null,receiver=null,subject_db=null,receiver_db=null,cc=null,cc_db=null;
suject=msg.getSubject();
sub_db=rs.getString("subject");
receiver=msg.getreceiver();
receiver_db=rs.getString("receiver");
cc=msg.getcc();
cc_db=rs.getString("cc"); String foldername;
if((subject.equals(sub_db)) && (receiver.equals(receiver_db)) && (cc.equals(cc_db)))
foldername="spam";
else
foldername="Inbox";
As you can see here, any of the variables can be null
. If this happens then it throws me NullPointerException. Is there any way I can do like,
String s1=null
and String s2=null
and if I compare if(s1.equals(s2))
then it returns me true
... I know above code is not gonna work to achieve this. But how do I do that in some other way ?
I am really sorry if I have failed to explain my problem properly...
I would appreciate any help..
Thank you..
Upvotes: 1
Views: 8338
Reputation: 2677
How about something like…
private boolean nullsOrEquals(string s1, string s2)
{
if (s1 == null)
return (s2 == null);
return s1.equals(s2);
}
if (nullsOrEquals(subject, sub_db) && [etc])
foldername="spam";
else
foldername="Inbox";
Upvotes: 4
Reputation: 964
If I understand you want to compare Strings even if they are null.
For that just add a condition in the if statement like:
if((string1 == null && string2==null) || string1.equals(s2))
{
//Your code
}
Upvotes: 1