- Java return arrays
- On Object.toString()
- Related questions
- On defining your own type
- See also
- Как вернуть массив из функции java
- Java вернуть массив строк
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- How to Return Array in Java from Method
- Returning One dimensional Array from Method in Java
- Returning Two dimensional Array from a Method in Java
- java - return array from method
- 5 Answers 5
Java return arrays
The toString() method of an array object actually doesn’t go through and produce a string representation of the contents of the array, which is what I think you wanted to do. For that you’ll need Arrays.toString() .
System.out.println(Arrays.toString(getItem(1)));
The notation [Ljava.lang.String is Java code for a String array — in general, the default string representation of an array is [L followed by the type of the array’s elements. Then you get a semicolon and the memory address (or some sort of locally unique ID) of the array.
That’s not an error. The JVM simply prints the address of the array since it doesn’t print its content. Try this and see what happens now?
System.out.println(getItem(1)[0]);
On Object.toString()
The reason why you’re getting such string is because arrays simply inherit and not @Override the Object.toString() method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character @ , and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
To return a String representation of an array that lists its elements, you can use e.g. Arrays.toString , and for «multidimensional» arrays Arrays.deepToString
Related questions
On deepEquals and deepToString for «multidimensional» arrays:
On defining your own type
It needs to be said that your usage of String[] is not the best design choice.
Things would be so much better had you defined your own class BasicItem supported by various enum , with as many final fields as is practical to enforce immutability; perhaps something like this:
public enum ItemType < KNIFE, SWORD, AXE; >public enum Attribute < SELLABLE, EDIBLE; >public class BasicItem < final String name; final String desc; final ItemType type; final int attackAdd; final int defenseAdd; final Setattributes; //. >
You should really take advantage all the benefits of good object-oriented design.
See also
- Effective Java 2nd Edition
- Item 50: Avoid strings where other types are more appropriate
- Item 25: Prefer lists to arrays
- Item 30: Use enums instead of int constants
- Item 32: Use EnumSet instead of bit fields
- Item 15: Minimize mutability
Как вернуть массив из функции java
Метод — это блок кода, который выполняет определенную операцию. Он может быть вызван из других частей программы, чтобы выполнить свою функцию.
Для того, чтобы вернуть массив из метода в Java , нужно указать тип возвращаемого значения метода как тип массива. Вот пример:
public class MyClass public static int[] createArray() int[] array = new int[5]; for (int i = 0; i array.length; i++) array[i] = i; > return array; > >
Этот код создаст метод createArray() , который возвращает массив из пяти целых чисел, заполненных значениями от 0 до 4. Чтобы вызвать этот метод и получить возвращаемый массив, можно использовать следующий код:
int[] myArray = MyClass.createArray(); // [0, 1, 2, 3, 4]
Java вернуть массив строк
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter
How to Return Array in Java from Method
Return Array in Java | In the previous tutorial, we have learned how to pass an array as an argument to a method while calling a method.
Although we can pass an array when calling a method, we can also return an array from a method, just like other simple data types and objects.
When a method returns an array, actually, the reference of the array is returned. For example, we create a class called ReturnArray from a method named display().
When we will call display() method, it will return an array num of integers (i.e. integer array). Look at the following source code.
Program code:
package arraysProgram; public class ReturnArray < public int[ ] display() < int[] num = ; return num; // Returning the reference of array that refers to the array elements. > > public class Test < public static void main(String[] args) < ReturnArray obj = new ReturnArray(); int[ ] num = obj.display(); for(int i = 0; i < num.length; i++) < System.out.println("num[" +i+ "] https://www.scientecheasy.com/2021/08/one-dimensional-array-in-java.html/">one dimensional array as its argument and it is made to return one-dimensional array.
The purpose of this method is to return a reference of array that refers to array elements, to a calling method.
In the main() method, we have called display() method using object reference variable obj and is to display them using for loop one by one on the console.
Now let’s understand the general syntax of how to return one dimensional and two-dimensional arrays from a method in java.Returning One dimensional Array from Method in Java
The general syntax of a method that can return a one dimensional array is as follows:
data-type[ ] method-name(argument) < // statements; // return arrayname; >
Here, data-type represents the type of array being returned. The use of one pair of brackets ([ ]) indicates that the method is returning one-dimensional array of type data-type.
Arguments can be optional that can be a scalar type or array type. The return statement returns the array name without any brackets.
The syntax of calling a method is as follows:
data-type[ ] arrayname = obj-ref.method-name(arguments);
Here, obj-ref is a reference to an object of the class of which the method is a member. The arguments (if any) are inputs to a method given from the calling method.
Let’s take a simple example program to compute the sum of elements in an array of integers.
Program code:
package arraysProgram; public class ArraySum < static int[ ] sum() < int[ ] data = ; return data; > public static void main(String[] args) < int sum = 0; int[ ] s = sum(); for(int i = 0; i < s.length; i++ ) < sum = sum + s[i]; >System.out.println("Sum of array elements: " +sum); > >
Output: Sum of array elements: 150
Returning Two dimensional Array from a Method in Java
We can also return two dimensional array from a method in java. The general syntax to declare a method that can return a two-dimensional array is as follows:
In the above syntax, the use of two pairs of square brackets indicates that the method returns two-dimensional array of type data-type.
The general syntax of calling a method is as follows:
data-type[ ][ ] arrayname = obj-ref.method-name(arguments);
Let’s take an example program where we will return two-dimensional array from a method. In this program, we will take two-dimensional arrays of int type that will represent two matrices.
Then, we will add them and get them into another two-dimensional array of int type that represents sum matrix. This sum matrix will be displayed on the console.
Program code:
package arraysProgram; public class TDArray < void show(int x[ ][ ]) < for(int i = 0; i < x.length; i++) < for(int j = 0; j < x[i].length; j++) System.out.print(x[i][j]+ " "); System.out.println(); >> int[ ][ ] sum(int[ ][ ] x, int[ ][ ] y) < int[ ][ ] z = new int[x.length][x[0].length]; for(int i = 0; i < x.length; i++) for(int j = 0; j < x[i].length; j++) z[i][j] = x[i][j] + y[i][j]; return z; // Returning 2D array. >> public class TDArrayfromMethod < public static void main(String[ ] args) < int[ ][ ] x = , >; int[ ][ ] y = , >; int[ ][ ] z = new int[x.length][x[0].length]; // Create an object of class TDArray. TDArray obj = new TDArray(); System.out.println("Matrix x: "); obj.show(x); System.out.println("Matrix y: "); obj.show(y); z = obj.sum(x, y); System.out.println("Matrix z: "); obj.show(z); > >
Output: Matrix x: 1 2 3 4 Matrix y: 5 6 7 8 Matrix z: 6 8 10 12
In this program, we have created a class TDArray with two methods show() and sum(). The show() method is declared with a two dimensional array as its argument.
The purpose of this method is to print elements of array passed to it. The sum() method is declared with two 2D arrays as its arguments and made to return a two dimensional array.
The function of this method is to display the sum of two 2D arrays passed to it and return the sum array (two dimensional array) to calling method.
In the main() method of class TDArrayfromMethod, two-dimensional arrays x and y are created with their values initialized and they are printed on the console.
After that the sum of arrays is calculated and assigned to another two-dimensional array z with statement z = obj.sum(x, y);. The sum array is then displayed on the console.
In this way, we can also think of passing and returning arrays of even arrays of higher dimensional also from a method.
4. Let’s take an example program where we will find out the list of prime numbers between the given two numbers. In this example, we will use Scanner class to get input from the keyboard. Concentrate on the following source code to understand better.
Program code:
package arraysProgram; public class Primes < // Test and return true if a number n is prime. static boolean prime(int n) < // Initially, isPrime is set to true. It become false if n is not prime. boolean isPrime = true; for(int i = 2; i static void findPrime(int num1, int num2) < System.out.println("List of prime numbers between " +num1+ " and " +num2+ " :"); for (int i = num1; i > > > import java.util.Scanner; public class PrimeTest < public static void main(String[] args) < // Create an object of Scanner class to connect with keyboard. Scanner sc = new Scanner(System.in); System.out.println("Enter your first number:"); int num1 = sc.nextInt(); System.out.println("Enter your second number:"); int num2 = sc.nextInt(); Primes.findPrime(num1, num2); >>
Output: Enter your first number: 10 Enter your second number: 30 List of prime numbers between 10 and 30 : 11 13 17 19 23 29
In this program, we have generated prime number series between two given numbers. A prime number is a number that is divisible by 1 and itself but not divisible by any other number. For example, the prime numbers between 2 and 10 are 2, 3, 5, and 7.
Hope that this tutorial has elaborated on all the important points concerning how to return array in java from a method. I hope that you will have understood the concepts of returning an array from a method in Java.
In the next tutorial, we will learn about arrays class in Java and its methods with examples. If you like this tutorial, please share it on the social sites for your friends.
Thanks for reading.java - return array from method
I just created a class, where data from the database is collected in an array. Now i just want to return the array from this method. But what i get is:
data_array cannot be resolved to a variable
public static String[] get_data() < conn = getInstance(); String[] data_array = null; if(conn != null) < Statement query; try < query = conn.createStatement(); String sql = "SELECT data_x FROM table_x"; ResultSet result = query.executeQuery(sql); result.next(); int count = result.getInt("data_x"); result.close(); data_array = new String[count]; for (int x = 1; x > catch (SQLException e) < e.printStackTrace(); >> return data_x_array; >
Invalid value for getInt() - 'value_in_table'
5 Answers 5
One more thing everyone forgot to mention
String[] data_array = new String[999]; for (int x = 0; x
will throw an ArrayIndexOutOfBoundsException. Possible solution
String[] data_array = new String[999]; for (int x = 0; x
You have defined your variable inside the while loop i.e. it is not visible to the return statement. Plus, you have defined your method as static void , meaning no return value is expected. Use static String [] instead.
Since its not accessible outside the block of while loop, compile is complaining about the same. Try this:
public static String[] get_data() < conn = getInstance(); String[] data_array = null; if(conn != null) < Statement query; try < query = conn.createStatement(); String sql = "SELECT data_x FROM table_x"; ResultSet result = query.executeQuery(sql); while (result.next()) < String data_x = result.getString("data_x"); data_array = new String[999]; for (int x = 0; x > > catch (SQLException e) < e.printStackTrace(); >> return data_array; >
Your declaration of the String[] is not in the same scope as the return statement.
You need to declare it in the beginning of the scope.
And you need to change the header of the function to:
public static String[] get_data()
There are two things to fix here:
public static void get_data()
This method is declared to return nothing. Change it to:
public static String[] get_data()
Your variable String[] data_array is declared in the while loop, therefore it is only known there. Your return statement is outside that loop, so it doesn't have access to it.
Move the variable outside the loop:
String sql = "SELECT data_x FROM table_x"; ResultSet result = query.executeQuery(sql); String[] data_array = new String[999];
Mind that you need to move the declaration and the initialization outside the while loop, or you will overwrite the previously stored data of that array by initializing it again. And also mind, that your for loop will overwrite the current data anyway . you should think about storing the row data in another array so, or it will be lost.