0

I'm having a problem with JavaMail and I just can't understand it. I want to search trough my mailbox for a mail with a certain subject (1234 in this case). I'm getting the subject with message.getSubject() and put it in an if statement and look if it's equal to 1234, but it gives me a NullPointerException every time. The weird thing is that if I'm trying to just printout the subjects of the mails (without the if statement), nothing seems to be wrong.

This is the code:

Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);

//Get all messages from inbox
Message[] messages = inbox.getMessages();

for (int i = 0; i < messages.length; i++) {
    if (messages[i].getSubject().equals("1234")) {
         System.out.println("Message found");
    }
}

This is the error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

At the following line:

if (messages[i].getSubject().equals("1234")) {

I hope you guys can help me with this problem.

Robin
  • 177
  • 1
  • 9

1 Answers1

1

This kind of code is dangerous in terms of NullPointerException's:

if (messages[i].getSubject().equals("1234")) {

You can get here two NullPointerException's:

  1. messages[i] can be null and throw one NullPointerException.
  2. messages[i].getSubject() can be null too and do the same thing.

My suggestion is to go the defensive route and re-write this to:

if(messages[i] != null && "1234".equals(messages[i].getSubject())) {

This will not throw a NullPointerException, since it checks if the possible candidates for NullPointerExceptions are not null (messages[i]) and the comparison is inverted by putting "1234" as the first comparison term. "1234" cannot be ever null.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • Thank you so much! I solved the problem by first checking if messages[i] is not null and if messages[i].getSubject() is not null. Within that if-statement, I got my old if-statement with the equals method. – Robin Nov 29 '17 at 17:41