Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I understand that JAVA enums are arranged to classes with private constructors and a collection of public static members. When linking two members of a given enum, I've always used .equals(), e.g.

public useEnums(SomeEnum a)

{

   if(a.equals(SomeEnum.SOME_ENUM_VALUE))

   {

       ...

   }

   ...

}

I just came across a few codes that use the equals operator == instead of.equals():

public useEnums2(SomeEnum a)

{

   if(a == SomeEnum.SOME_ENUM_VALUE)

   {

       ...

   }

   ...

}

Which operator is the one I should be practicing?

1 Answer

0 votes
by (46k points)

Both .equals() and == are technically correct, If you check the source code you will realize that .equals() refers to == .

So, the basic difference between them is that == will never throw a NullPointerException whereas .equals() will.  You can test this by running this syntax:

enum Color { BLUE, GREEN};

Color nothing = null;

if (nothing == Color.BLUE);                 // runs fine

if (nothing.equals(Color.BLUE));         // throws NullPointerException

And, == is subject to type compatibility check at compile time whereas .equals() isn't. Test this using the following Syntax:

enum Color { BLUE, GREEN };

enum Chiral { LEFT, RIGHT };

if (Color.BLUE.equals(Chiral.LEFT));       // compiles fine

if (Color.BLUE== Chiral.LEFT);               // DOESN'T COMPILE!!! Incompatible types!

Coming to your final question, I prefer to use == instead of .equals() as it's faster and null safe.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...