Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array from method - java

Tags:

java

arrays

private static Coordinate[] getCircleCoordintaes() {  
  Coordinate coordinates[] = {new Coordinate(0, 0)};
  return coordinates;   
}

Above program working fine. In the above program for return the coordinate array first initialized the array using this line

Coordinate coordinates[] = {new Coordinate(0, 0)}; 

and then return coordinates.

But when I try to return directly below line then got exception.

{new Coordinate(0, 0)} 

Actually I am trying to find a way to return coordinate array directly. I want to skip the assigning step. May be I am doing something wrong.

How to return this array directly? Any suggestion?

like image 660
Shiladittya Chakraborty Avatar asked Jul 16 '26 11:07

Shiladittya Chakraborty


1 Answers

return new Coordinate[] { new Coordinate(0, 0) }

To elaborate, the construct you are using ({new Coordinate(0, 0)};) is called Array initilizer and as per JLS can be used only in declaration or as part of Array creation expression.

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.

ArrayInitializer:
    { VariableInitializersopt ,opt }
like image 85
Bohuslav Burghardt Avatar answered Jul 19 '26 01:07

Bohuslav Burghardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!