Question

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 ?

Était-ce utile?

La solution

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!")

Autres conseils

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");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top