do you mean like this?

int[] dim1 = myObject.getCoord();

public int[] getCoord() {
    return new int[] {y1, x1} ;
}

only one array is ever created, by the method call, and only has one reference, dim1.

but ideally you probably don't want a "get" method to be creating new things, as just by looking at the declaration you might not expect that. personally, i'd prefer

int[] dim1 = myObject.createCoord();

public int[] createCoord() {
    return new int[] {y1, x1} ;
}

which makes it explicit that the method is "creating" a thing.

Answer from John Gardner on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-return-an-array-in-java
How to Return an Array in Java? - GeeksforGeeks
July 23, 2025 - Here we will be considering three examples for scenarios. ... Any built-in data type's array be integer, character, float, double all can be returned simply uses return statements keeping in mind the points listed above.
Discussions

How do you return an array in a method?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
26
15
April 22, 2021
Returning Arrays in Java - Stack Overflow
@Dimenein Nope, that wonโ€™t print the array in a useful way. Try it and youโ€™ll see what I mean ;) 2020-08-09T12:49:49.31Z+00:00 ... I want it to return the array without having to explicitly tell the console to print. 1) Java does not work that way. Nothing ever gets printed implicitly. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Return array of multiple different objects? - Software Engineering Stack Exchange
The members can have descriptive ... Arrays. You can pass around multiple values in one object if you ever need them together in another place of your program (and experience teaches that you often will). ... Thanks for the answer! What if I don't need those values together in any other place of the program? Would you still prefer to create a class? ... @AndreasBraun Yes, creating a class is still better for the reasons of type-safety and mnemonic names. (If Java allowed you ... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
April 6, 2017
java - Return array pointers vs. populating an array inserted as a parameter? - Software Engineering Stack Exchange
So in Java you can (and should) follow the natural data flow, i.e. returning a fresh array from the method. In C, although it's counter-intuitive, it's often better to have the caller provide the array - C programmers are used to that style. More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
September 7, 2017
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 408623 โ€บ java โ€บ return-array-method
how to return an array from a method (Beginning Java forum at Coderanch)
Hi Manishekar, there is an easy way to return an array from a method in java. You can call a method by value or by reference. one thing here to note that Java always passes arrays and vectors by reference. So, any modification to the array elements in another function would mean that the original ...
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_arrays.asp
Java Arrays
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets [ ] :
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how do you return an array in a method?
r/javahelp on Reddit: How do you return an array in a method?
April 22, 2021 -

Today, I had a interview but I failed miserably in the first coding test. And before I can finish it, the interviewer just hung up the phone....sob sob

I am completely stumped how to do this question and have spent the last 2 hours figuring out to no avail and I hope to be able to get some helps here.

So, you are given an array = {1,2,6,4,5}

And a target no say 10.

The method must return the answer in {6,4}.

How can I achieve it ?

Here's my lame attempt:

public static int[][]ab(int[]arr, int target){
		target = 10;
		int[][]temp = null;
		int a = 0; int b = 0;
		int sum = 0;
		for(int i = 0; i < arr.length; i++) {
		for(int j = i; j < arr.length; j++) {	
			a = arr[i];
			b = arr[j];
			if ( a + b == 10) {				
				System.out.printf("Pair : " + arr[i], arr[j] );
			}
		}		
		}
return temp;// i do not know how to put arr[i] and arr[j] and store it in a array 
		}

Tks.

Top answer
1 of 8
11
Today, I had a interview but I failed miserably in the first coding test. And before I can finish it, the interviewer just hung up the phone....sob sob You should probably hold off on interviews for a while. You have a lot of basics to learn still, and should focus your time on learning those things rather than trying to interview for jobs you're not yet qualified for.
2 of 8
9
Why is your method trying to return a 2d array, when a 1d array is probably needed? I've put a cleaner version of your above method below, keeping the logic which is correct, adding a JavaDoc to better explain the problem which you are trying to solve (or, at least, what I think the problem you're trying to solve is supposed to be), fixing the method signature, and leaving a couple of TODOs for the stuff you haven't done correctly. Again, this is operating under the assumption that you needed to return a one-dimensional array, not a 2d array. /** * Given a target number and an input array, this method should * return an array of two integers, these integers being the two * numbers from the input array which add up to the 'target'. * @param arr the array containing the numbers which should add up to the 'target' * @param target we are looking for the numbers in 'arr' that add up to this * @return a two-index array containing the two numbers from 'arr' which 'target' is the sum of. */ public static int[] ab(int[] arr, int target){ // we will put the results in here when we find them final int[] results = new int[2]; for(int i = 0; i < arr.length; i++) { final int lhs = arr[i]; // the left hand side number we will be testing for (int j = i+1; j < arr.length; j++){ // i+1 is used so we don't test index i against itself final int rhs = arr[j]; // the right hand side number // TODO: work out if lhs + rhs are equal to 'target'. // TODO: If they are, put them in 'results' // TODO: but, if they are, how are you going to break out of the loop, now that you have a result? :thonking: } } // and we return the 'results' array. we can return it just like how we'd return any other data type. return results; }
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ how to return an array in java? a detailed guide (+examples)
How To Return An Array In Java? A Detailed Guide (+Examples)
January 2, 2025 - Returning an array in Java involves creating it in a method, adding values if needed, and using return to pass it back to the calling code for use.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arrays-in-java
Arrays in Java - GeeksforGeeks
An integer array arr is declared and initialized in the main method. The sum() method is called with arr as an argument. Inside the sum() method, all array elements are added using a for loop.
Published ย  2 weeks ago
๐ŸŒ
Quora
quora.com โ€บ How-do-I-return-a-string-array-in-Java
How to return a string array in Java - Quora
Java Data Structures and ... ... Java (programming languag... ... Returning a string array in Java is straightforward: create (or obtain) the array, declare the method to return String[], and use the return statement.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ how-to-return-an-array-in-java
How to Return an Array in Java? (from a Method) | FavTutor
September 26, 2024 - Java always passes arrays and vectors by reference, so any modification to the array elements in another function would mean that the original array would also be modified similarly. The parameter list is structured accordingly. It is always wise to send the length of the array to the function because the calculation of length within the function would be pretty tedious. class Array { public void returnArr(int arr[],int len) { for (int i = 0; i < len ; i++) { System.out.print(arr[i]+" "); } } public static void main(String args[]) { Array obj = new Array(); int arr[] = { 1, 2, 3, 4, 5 }; obj.returnArr(arr,arr.length); } }
Top answer
1 of 3
5

In classical C, returning an array from a function isn't as easy as in Java. That's why C functions often choose to populate an array passed in from the caller, whereas Java methods typically follow the natural data flow, i.e. returning the results as array.

So in Java you can (and should) follow the natural data flow, i.e. returning a fresh array from the method. In C, although it's counter-intuitive, it's often better to have the caller provide the array - C programmers are used to that style.

Let me explain my reasoning:

C style

If you want to return an array from a function, you have to allocate it dynamically (it can't be on the stack as that wouldn't survive leaving the function, and it can't be static, because then multiple function calls would get mixed up). To the caller, that means that he gets responsible for eventually freeing the array.

The caller needs to know how long the array is, so he doesn't access invalid elements. As an array result (e.g. int[]) is in fact just a pointer to its element type (int *), there's no place to communicate the length.

So in C, there's no easy and natural way to return an array from a function.

(Of course, that's only classical C, and later versions added much of the features that classical C lacked, but many library functions were already defined early...).

Java style

Arrays are always created in dynamic memory (on the heap), but that's managed by the JVM. So the caller has no duty of freeing any memory, because that's done by the garbage collector.

Also there's no problem with the array length as Java arrays know their length.

2 of 3
5

From a semantic perspective, returning an array from the method suggests that it's a different array than the one you passed in. That's why the accepted C style, when modifying an array in place, is to modify the array that is passed in, in place. Returning a new collection is more common in Java than it is in C, which is why you see it being passed out of the function as a return value.

An array in C is really just a pointer to a typed value; C doesn't even know how long an array is if you allocated it dynamically, making it difficult for a caller to handle a returned array. Arrays in Java contain metadata, such as the length of the array and the type of its members, making it easier for methods to return new arrays and for callers to consume them.

Note that you can still modify an existing array in-place in Java if you wish, in which case you would do the same thing in Java that you would in C: modify the passed-in array parameter in-place.

C pointers and Java references are not the same thing, even though they are used to accomplish similar objectives. In C, a pointer is an actual memory address. Pointer arithmetic is possible in C, where it is actually used to allocate memory and dereference array members and struct members.

In Java, references are an implementation detail, not a memory address. You cannot perform pointer arithmetic on them, nor can you make any assumptions at all about how they work under the hood from a memory perspective, because the Java language specification does not stipulate how they are to be implemented.

This difference is further highlighted in the treatment of zero-length arrays: they don't exist in C, except as the last member of a struct.

๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ print-a-returned-array
Print a returned array (Example) | Treehouse Community
August 5, 2016 - I want it to look something like ...(createIntArray(C.length)); } ... When you ask Java to print an array it just prints out the memory address of the array....
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ find
Array.prototype.find() - JavaScript | MDN
The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned. The find() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ โ€บ js_arrays.asp
W3Schools.com
But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John:
๐ŸŒ
Quora
quora.com โ€บ Why-is-it-OK-to-return-an-array-in-Java-but-not-in-C
Why is it OK to return an array in Java but not in C? - Quora
Answer (1 of 5): We have first do understand how the two languages represent data: [code]a=b; a.x=2; b.x=3; [/code]What is the value of [code ]a.x[/code] now? * in JAVA will be 3 * In C will be 2 To have the same effect in C you must have [code ]a[/code] and [code ]b[/code] as pointers, so th...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arraylist-in-java
ArrayList in Java - GeeksforGeeks
This constructor is used to build an array list with the initial capacity being specified. ... Now, Using the constructors we have got ArrayList for further operations like Insertion,Deletion and Updation of the elements in ArrayList. ... import java.util.*; class GFG{ public static void main(String args[]){ // Creating an Array of string type ArrayList<String> al = new ArrayList<>(); // 1.
Published ย  2 weeks ago