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

# Thread: Why does this equal that?

1. ## Why does this equal that?

Why is it that this method returns true? I'm supposed to write an equals method that returns true if both rectangles are similar (My assumption of a "similar rectangle" is one which has the same ratio of height:length as the other rectangle).

```public class Rectangle {

public int width;
public int length;

public Rectangle(int width, int length){
this.width = width;
this.length = length;
}
public static void main(String[] args) {
Rectangle r = new Rectangle(2,4);
Rectangle s = new Rectangle(6,13);
boolean n = s.equals(r);
System.out.println(n);
}

public boolean equals(Rectangle rectangle){
if((this.width / this.length) == (rectangle.width / rectangle.length))
return true;
else
return false;
}```

Shouldnt s.equals(r) return false?

2. ## Re: Why does this equal that?

Add some System.out.println in your equals method to check what the values of each division calculation. This will give you an indication as to why this is the case - and why are 2 rectangles equal when their width/length ratio are equal? Does that mean 6x1 is equal to 12x2?

3. ## Re: Why does this equal that?

In addition to Copeg's answer, you're doing integer division, which truncates to the next smallest integer (1 / 2 = 0, 4 / 3 = 1, etc.). That's why it's returning true for a 2x4 and a 6x13 rectangle.