1

Here is my code :

if (ChoixPortCom.equals(null) == true ) JOptionPane.showMessageDialog(null, "Choose Port COM");

and I get the famous java.lang.NullPointerException

My JCombobox is filled like : 1st -> nothin/empty null no String nothing 2nd -> COM1 3nd -> COM2 ....

Why is "if" condition not right ?

D3fman
  • 85
  • 2
  • 11

2 Answers2

2

choixPortCom.equals(null) will never be true. If choixPortCom is not null, then the expression will return false as expected. If choixPortCom is null, then the expression will throw a NullPointerException, since you are attempting to call a method on null; this is what's happening in your case. The appropriate way to check for null is:

if (choixPortCom == null)  // I've assumed a more common naming convention

There is also an Objects class in Java 7 that has some useful methods for null-checking. For example, Objects.requireNonNull():

Objects.requireNonNull(choixPortCom, "input can't be null!")
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

It should be

if (ChoixPortCom == null)

Now if ChoixPortCom is null it will throw a NullPointer because you are trying to invoke a method (equals) on a null reference.

And something I like to think of as a best practice is to always use brackets:

if (ChoixPortCom == null) {
    JOptionPane.showMessageDialog(null, "Choose Port COM");
}
bknopper
  • 1,193
  • 12
  • 28
  • Can you do this if ChoixPortCom is a String ? – D3fman Mar 13 '14 at 15:02
  • Definitely. String is also an object. – bknopper Mar 13 '14 at 15:02
  • yep you were right, it works. I did with String.equals() because we told me to this when I compare with a String. Never mind, thanks. – D3fman Mar 13 '14 at 15:04
  • And please follow java code conventions , variables names starts with lower-case and follow a camel-case style – nachokk Mar 13 '14 at 15:05
  • The comparison would then be with a String value such as stringObject.equals("D3fman"); Even better: "D3fman".equals(stringObject); (now if stringObject == null you don't get a nullpointer) – bknopper Mar 13 '14 at 15:06