-4
import java.awt.Rectangle;

public class AddTester {
   public static void main(String[] args) {

    Rectangle box = new Rectangle(5, 10, 20, 30);
    System.out.println(box);
    //output: java.awt.Rectangle[x=5,y=10,width=20,height=30]    

    box.add(0, 0);
    System.out.println(box);
    //output: java.awt.Rectangle[x=0,y=0,width=25,height=40]
   }
}

Why does the width and the height change after calling the add(int newx, int newy) method on the box object?

I actually just drew the rectangle on a cartesian system on paper. Now it looks that it might be because another rectangle is inserted as an extension of the current rectangle. Hence, it extends in width and height. Is this correct?

Example

Dorkymon
  • 9
  • 5
  • 1
    Just read the documentation. It tells you exactly what the method does. – Boann Jun 16 '17 at 14:29
  • You make the rectangle bigger to include the given point. Naturally, its width and/or height must change! – king_nak Jun 16 '17 at 14:32
  • @king_nak Yeah, it occurred to me after drawing. The name of the arguments of the add method (newx, newy) led me to think that the rectangle will only change these values. – Dorkymon Jun 16 '17 at 14:40

1 Answers1

2

You will want to first look at the Java API whenever you have questions about how a core Java method is supposed to behave.

public void add(int newx,  
                int newy)  

Adds a point, specified by the integer arguments newx,newy to the bounds of this Rectangle.
If this Rectangle has any dimension less than zero, the rules for non-existant rectangles apply. In that case, the new bounds of this Rectangle will have a location equal to the specified coordinates and width and height equal to zero.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373