tags:

views:

86

answers:

5

Take this example:

public class foo
{
    public int[] func()
    {
        int arr[] = new int[3];
        // here initialised the array

        return arr;
    }
}

I'm not experienced with Java, but I know a little of C/C++.

+2  A: 

Yes it should be OK. Because Java arrays are allocated on heap not on stack. They wound't be collected after the function call returns.

Ravi Gummadi
Note that as mentioned elsewhere, in C++ the caller would have to be aware to delete the `new`ed array, even though it is similarly allocated on the heap.
Marc Bollinger
+6  A: 

Yes, it's completely OK, because garbage collection is done when there is no further reference to the object. You can also find the array size by using length inside (arr.length) or outside (e.g. aFoo.func().length) the method.

Mohsen
A: 

Yes in both Java and C++.

The catch is in C++, you will heave to delete[] it manually sometime later to avoid memory leaks; while in Java, the garbage collector will do its thing once there is no more references to the array, so you don't have to do anything.

Lie Ryan
A: 

It is ok to return the local array, but you must substantiate the returned data in the rest of your program so it continues serving a purpose.

Relate the data to something new.

JMC
A: 

It is perfectly OK in C# world.

You also can do this: return new int[] {1,2,3,4};

Patrol02