You still need to create the array, even if you do not assign it to a variable. Try this:

public int[] getData() {
    return new int[] {a,b,c,d};
}

Your code sample did not work because the compiler, for one thing, still needs to know what type you are attempting to create via static initialization {}.

Answer from Perception 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 - The elements of the array are stored in a way that the address of any of the elements can be calculated using the location of the first index of the array using a simple mathematical relation. Arrays in Java are different in implementation and usage when compared to that in C/C++ although they have many similarities as well. Here we will discuss how to return an array in java.
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
memory management - How to return an array in one line in Java? - Stack Overflow
"While dim1 will live, dim2 lives for just two lines and then goes to gc." This is not true. It depends on what you do with the returned array. If the result (aka. the reference address of the new array in the method) is stored in some reference (as you do in your example), it will not be ... More on stackoverflow.com
🌐 stackoverflow.com
java return array in method - Stack Overflow
I'm doing my first steps in java, so my question is simple - I have an array with 8 integers and I want to return an array that contains the odd index elements from the original array. what's wrong... More on stackoverflow.com
🌐 stackoverflow.com
A comparison of Rust’s borrow checker to the one in C#
Very interesting! I've been programming in C# for years before switching to rust, but never noticed the similarities More on reddit.com
🌐 r/rust
41
150
October 27, 2024
🌐
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 - Similarities Between Java Vs. C++ ... Learn how to return an array in Java by creating the array inside a method, populating it with values if necessary, and using the return keyword to send it back to the calling code for further use.
🌐
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 - This is a complete guide on how to pass and return an array in Java.
🌐
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; }
🌐
Coderanch
coderanch.com › t › 408623 › java › return-array-method
how to return an array from a method (Beginning Java forum at Coderanch)
November 2, 2007 - . . . Java always passes arrays and vectors by reference. . . . I see Stephan has already explained your mistake. Thank you for giving us that link It is unfortunate that people still write that sort of rubbish in tutorials. Please don't call what you wrote a function; call it a method. It doesn't actually represent a function because it takes no input. ... Hi, I want to notice some hits, so when your write return a, you would know that you return an object reference, not the returned array, probably there were two possible to return the desired array, 1 - you tape new int[]{}{} or you use for loop and change the method to void type
Find elsewhere
🌐
Scaler
scaler.com › home › topics › how to return an array in java
How to Return an Array in Java - Scaler Topics
May 4, 2023 - The array follows the rule of pass-by-reference when they pass as an argument in the particular method. The return statement is used in the user-defined or predefined method to return an array from the method.
🌐
Delft Stack
delftstack.com › home › howto › java › java return array
How to Return Array in Java | Delft Stack
February 2, 2024 - To do this, we use Arrays.toString() that takes an array as the only argument and converts the array to a string. import java.util.Arrays; public class ReturnAnArray { public static void main(String[] args) { String intArrayAsString = ...
🌐
W3Schools
w3schools.com › java › java_arrays.asp
Java Arrays
Use new with a size when you want to create an empty array and fill it later. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Software Testing Help
softwaretestinghelp.com › home › java › how to pass / return an array in java
How To Pass / Return an Array In Java
April 1, 2025 - This tutorial will explain how to pass an array as an argument to a method and as a return value for the method in Java with simple examples.
🌐
TutorialsPoint
tutorialspoint.com › How-to-return-an-array-from-a-method-in-Java
How to return an array from a method in Java?
July 30, 2019 - import java.util.Arrays; import java.util.Scanner; public class ReturningAnArray { public int[] createArray() { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created:: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } return myArray; } public static void main(String args[]) { ReturningAnArray obj = new ReturningAnArray(); int arr[] = obj.createArray(); System.out.println("Array created is :: "+Arrays.toString(arr)); } }
Top answer
1 of 3
8

1)You cannot have methods inside method in Java. Move your oddIndex() methods outside main() method.

2) And you cannot local variables of a method in another method. So I moved your variable j to oddIndex() method

public class Main {

    public static void main(String[] args) {

        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };

        System.out.println("1.e odd index numbers in array : " + oddIndex(arr));

    }

    public static int[] oddIndex(int[] array) {
        int j = 0;
        int newArrSize = array.length;
        if ((newArrSize % 2) != 0) {
            newArrSize--;
        }

        int[] newArr = new int[newArrSize];

        for (int i = 0; i < array.length; i++)
            if ((array[i] % 2) == 0) {
                newArr[j] = array[i];
                j++;
            }
        return newArr;

    }

}

And also, as Jhamon commented, your method name and logic inside are not matched. Odd index != odd value.

2 of 3
4

Issue with your code:

  • you can not define method inside another method.
  • If you want to return an array that contains the odd index elements from the original array. you should check index%2!=0 instead of checking array value of that index.

try this

public class Main {
      public static void main(String[] args) {
         int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
         System.out.println("1.e odd index numbers in array : " +  Arrays.toString(oddIndex(arr)));

    }



     public static int[] oddIndex(int[] array){

         int[] newArr = new int[array.length];
         int j=0;
         for (int i = 0; i < array.length; i++){
             if ((i % 2) != 0) {
                 newArr[j++] = array[i];

             }
         }
         return Arrays.copyOf(newArr, j);
    }
 }

output:

1.e odd index numbers in array : [2, 4, 6, 8] // odd index elements from original array
🌐
W3Docs
w3docs.com › java
Returning Arrays in Java
To return an array in Java, you can simply specify the array type as the return type of the method.
🌐
GoLinuxCloud
golinuxcloud.com › home › java examples › how to return an array in java [practical examples]
How to return an Array in Java [Practical Examples] | GoLinuxCloud
February 22, 2022 - There are three different ways to return an array from a function in Java as listed below: Return an array of primitive type, Return an array of objects, Return a multidimensional array
🌐
Scientech Easy
scientecheasy.com › home › blog › how to return array in java
How to Return Array in Java - Scientech Easy
February 14, 2025 - In this tutorial, you will learn how to return an array from a method in Java.
🌐
Emory
mathcs.emory.edu › ~cheung › Courses › 170 › Syllabus › 09 › array-return.html
Emory
Java program that returns an array: Explanation: How to invoke the returnArray method: Example: Example Program: (Demo above code) &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp ·
🌐
JavaBeat
javabeat.net › home › how to return an array in java?
How to Return an Array in Java?
November 30, 2023 - To return an array in Java, use the “return” keyword before the array name after the array declaration and initialization and use the “for” loop to select the array elements.
🌐
Studytonight
studytonight.com › java-examples › how-to-return-an-array-in-java
How to Return an Array in Java - Studytonight
January 28, 2021 - In the below program, we passed an Array inside the method reverseArray() then we reversed an array and returned it using the return keyword and after that, it is assigned to the original array.