1

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..

3 Answers 3

4

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";
Sign up to request clarification or add additional context in comments.

Comments

3

if((s1 == null && s2 == null) || s1.equals(s2))

4 Comments

This should be a comment. No? :p
Or more precisely, to cover your example and avoid the NPE... if((s1 == null & s2 == null) || s1.equals(s2))
@Elite, Sorry, just joined and can't comment until I get some rep :( Try to help when I can but I'm only able to post answers at the moment.
Edit the full expression into the answer please
1

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
}

1 Comment

Thanks all for your response..Finally I ddid it like. private static boolean nullsOrEquals(String s1, String s2) { if(s1 == null) { if(s2 == null) { return true; } return false; } if(s2 == null) { return false; } return s1.equals(s2); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.