Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • Re: Common Java Mistakes

    Problem description: == operator or equals() method
    Problem category: Logic Problems

    Diagnosis Difficulty: Easy-Medium
    Difficulty to Fix: Easy-Medium


    A common problem among many beginning (and some not so beginning) programmers is the incorrect use of the equal operator and equals() method.

    The equals operator is used exclusively to compare the value of primitives, or to compare the references (memory addresses) of objects.

    // proper usage of the == operator
    int a = 5;
    int b = 5;
    if(a == b) // test if the value a equals the value b
    {
        System.out.println("a and b have the same value");
    }

    The equals() method is used to define when two object values are equal. They do not necessarily have to be the same object (though, if they are they should return true for equals() as well as ==).

    public Class Point
    {
        public int x, y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
     
        /**
          * Two points are equal if they have the same x and y value
          */
        public boolean equals(Point o)
        {
            if(o == null)
            {
                return false;
            }
            return o.x == x && o.y == y;
        }
     
        public static void main(String[] args)
        {
            Point p1 = new Point(4,5);
            Point p2 = new Point(4,5);    // p2 is a physically in a different location in memory, but it contains the same value as p1
            if(p1.equals(p2))
            {
                System.out.println("p1 and p2 have the same value");
            }
            if(p1 == p2)
            {
                System.out.println("p1 and p2 are the same object in memory");
            }
        }
    }

    Suggested fixes

    You must determine which behavior you want in your particular instance. Sometimes you do want to compare two objects to see if they are the exact same object. However, in the majority of cases you will want to use the equals() method when comparing two objects.
    Common Java Mistakes helloworld922
    1
    1. basavaraj -
      this was helped for freshers