I need help to build a method that returns an array

Viewed 138

So, i'm a beginner in Java, and my teacher wants me to build a method that returns an Array of two elements. This is what i've made

public int[] getXY() {
    int[] a = new int[2];
    a[0]=getX();
    a[1]=getY();
    return a;
}

getX and getY returns this.x and this.y respectively. So obviously this method returns the reference to the array, not the elements of the array itself, which is what i want to do, but i've no ideas. He made it clear that the method has to return an Array of two elements, so that's why i didn't make it with String. Any suggestions?

1 Answers

What you have got is the correct solution. In Java, you cannot get the "array itself." All you can have is a reference to the array.

This sounds like a simple miscommunication. Since you can only have a reference to an array (or to any object in general) - never the array itself, people sometimes use loose language and say "this method returns an array" when they mean "this method returns a reference to an array".

Related