The Wayback Machine - https://web.archive.org/web/20240924232426/https://www.geeksforgeeks.org/comparing-enum-members-java/
Open In App

Comparing enum members in Java

Last Updated : 12 Jul, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : enum in Java, == vs equals

In Java, enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a special kind of Java class. An enum can contain constants, methods etc. enum can be defined as a group of named constant.

There are two ways for making comparison of enum members :

  • By using == operator
  • By using equals() method

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method. But the question is if we have two ways for comparing two members of enum, then which one is better?

Both == operator and .equals() method are meant for comparison only. But there are few differences :

  • == operator never throws NullPointerException whereas .equals() method can throw NullPointerException.
  • == is responsible for type compatibility check at compile time whereas .equals() method will never worry about the types of both the arguments.

Lets have a look on the programs for better understanding:




// Java program to illustrate enum members comparison
class EnumDemo {
    public enum Day { MON,
                      TUE,
                      WED,
                      THU,
                      FRI,
                      SAT,
                      SUN }
    public static void main(String[] args)
    {
        Day d = null;
  
        // Comparing an enum member with null
        // using == operator
        System.out.println(d == Day.MON);
  
        // Comparing an enum member with null
        // using .equals() method
        System.out.println(d.equals(Day.MON));
    }
}


Output:

false
Exception in thread "main" java.lang.NullPointerException

Explanation: In the above program, we are comparing an enum member with a null. When we use == operator for comparison, then we are not getting any Exception whereas when we use .equals() method then we are getting NullPointerException.
Therefore we can conclude that when we use == operator for enum member comparison, then it does not throw any Exception but .equals() method throw an Exception.

Another Example:




// Java program to illustrate enum members comparison
class EnumDemo {
    public enum Day { MON,
                      TUE,
                      WED,
                      THU,
                      FRI,
                      SAT,
                      SUN }
    public enum Month { JAN,
                        FEB,
                        MAR,
                        APR,
                        MAY,
                        JUN,
                        JULY }
    public static void main(String[] args)
    {
        // Comparing two enum members which are from different enum type
        // using == operator
        System.out.println(Month.JAN == Day.MON);
  
        // Comparing two enum members which are from different enum type
        // using .equals() method
        System.out.println(Month.JAN.equals(Day.MON));
    }
}


Output:

error: incomparable types: Month and Day

Explanation:In the above program, we are comparing an enum member with an another enum member. When we use .equals() method for comparison then we are not getting any Compilation Failure(CF) whereas when we use == operator then we are getting Compilation Failure(CF) saying “incomparable types” . Therefore we can conclude that when we use == operator for enum member comparison then it performs type compatibility check at compile time whereas .equals() method will never worry about the types of both the arguments(it will just give “false” for incomparable types).



Similar Reads

Java.lang.Enum Class in Java
Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create obje
8 min read
Accessing Protected Members in Java
In Java, there are four types of access modifiers. These are public, private, default, and protected. To get the idea of these modifiers, you can refer to access modifiers in java. In this article, we discuss the accessibility of protected members in different cases. Now let us discuss various scenarios of accessing protected members which are list
6 min read
Java - Calling Non Static Members Directly From Constructor Without Using the Object Name
Java is an Object-Oriented Programming(OOP) language. We need to create objects in order to access methods and variables inside a class. However, this is not always true. While discussing static keywords in java, we learned that static members are class level and can be accessed directly without any instance. Here we will be discussing how we can a
3 min read
Structure and Members of the Java Program
When we are writing any program in any language, we need to follow a standard structure for writing the program which is recommended by the language experts. A Java program may contain many classes of which only one class will have a main method. The class will contain data members and methods that operate on the data members of the class.  To writ
5 min read
Iterating over Enum Values in Java
Enum in Java is a data type that contains a fixed set of constants. A Java enum type is a special kind of Java class. An enum can contain constants, methods, etc. Given below is a demonstration of how to declare an enum: Java Code // Demonstrates the declaration of enum public enum season { Spring, Summer, Monsoon, Autumn, Winter } Iterate over Enu
3 min read
How to implement an Interface using an Enum in Java
Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. We have already discussed the basics of enum, how its declared in the previous article. In th
3 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Why Enum Class Can Have a Private Constructor Only in Java?
Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name. Enum without a constructor: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Enum with a constructor: enum Size { SMALL("The size is small."), MEDIUM("The size is medium."),
2 min read
Difference Between ordinal() and compareTo() in Java Enum
Enumerations serve the purpose of representing a group of named constants in a programming language. If we want to represent a group named constant then we should go for Enum. Every enum constant is static. Hence, we can access it by using enum Name. Example: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }ordinal() Metho
3 min read
Advantages and Disadvantages of using Enum as Singleton in Java
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards. Advantages of using Enum as Singlet
3 min read
Enum with Customized Value in Java
Prerequisite : enum in Java By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that. Examples: enum Fruits { APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”); } In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES with have their own di
2 min read
enum in Java
In Java,Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. What is Enumeration or Enum in Java?A Java enumeration is a class type. Although we don't
9 min read
Comparing Streams to Loops in Java
A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation performs a function. Ideally, a function's output
7 min read
Difference between comparing String using == and .equals() method in Java
Both the equals() method and the == operator are used to compare two objects in Java. The Java string equals() method, compares two strings and returns true if all characters match in both strings, else returns false. The == operator compares the reference or memory location of objects in a heap, whether they point to the same location or not.Whene
6 min read
Problem in comparing Floating point numbers and how to compare them correctly?
In this article, we will see what is the problem in comparing floating-point numbers and we will discuss the correct way to compare two floating-point numbers. What is the problem in comparing Floating-Point Numbers usually?Let us first compare two floating-point numbers with the help of relational operator (==).Example: Using "==" for comparison C
7 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Article Tags :
Practice Tags :