0

following snippet of code astonished me

   public class enums
{
    enum days
    {
        M,T,W,TH,F,S,SU;
    }
    public static void main(String []args)
    {
        days d1=days.M;
        days d2=days.M;

        if(d1==d2)
        {
            System.out.println("equal by == operator"); //  
        }
        if(d1.equals(d2))
        {
            System.out.println("equal by equals method");
        }

    }
}

output is :

equal by == operator

equal by equals method

behaviour of equals methods is intuitive and but behaviour '==' is supposedly to be constant.Shouldn't "d1==d2" return false because they are two completely different objects and from what i know there is no operator overloading in java...how come expression in second 'if' turn out to be true...

so does that mean there is only one object created for each enum constant? that's not true right because it can have something similar to instance methods.....

so how exactly can we visualize enums......

manifold
  • 437
  • 6
  • 23
  • 2
    Possible duplicate of http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals?rq=1 – T. Claverie May 20 '16 at 09:19
  • tl;dr: technically speaking, enums are singletons and therefore yu can use both `==` and `equals`. – Turing85 May 20 '16 at 09:19
  • "Shouldn't "d1==d2" return false because they are two completely different objects" No, they're not two completely different objects, even if you weren't doing this on enum values. – Andy Turner May 20 '16 at 09:20

0 Answers0