File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Returning an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Returning an array" Watch "Returning an array" New topic
Author

Returning an array

V��r� Tunnus
Greenhorn

Joined: Mar 29, 2006
Posts: 8
Hi. I'm currently facing problems with this kind of thing: I need to do different kind of calculations and then return those results in a new array (I've one previous array but it doesn't affect to this?). How should I do this thing. Am I right if I say that I need first create a new array, then put those results to that array and then return it? Ok, if I'm right then there is only one problem, I couldn't find information how to return an array. Does it work then like this:

return myArray[];

This is what my logic says, but I can't test this return-thing yet so I hope that you'll inform me.
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Originally posted by V��r� Tunnus:

This is what my logic says, but I can't test this return-thing yet so I hope that you'll inform me.


Why can't you test it yet? You should test your hypotheses as soon as possible, even if it means writing a trivial class to do the testing. That's the best way to learn.
Kaush Kane
Ranch Hand

Joined: May 22, 2006
Posts: 37
Here is the way one can return array:

class RArray{
public static void main(String args[])
{
int array1[] = new int [5];
array1 = RArray.return_array();
for(int i=0; i<5 ; i++)
{
System.out.println(array1[i]);
}
}
static int[] return_array()
{
int array2[] = {1,2,3,4,5};
return array2;
}
}
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780

  • The preferred syntax for array variables is "String[] args", not "String args[]".
  • The allocation of "new int [5]" and its assignment to variable array1 is pointless, since array1 is assigned to in the next line.
  • The for loop assumes that the method is returning an array of length (at least?) 5. It's better to use the length atribute.

  • Fixing this yields:
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Returning an array