Hello. I am trying to return an array and print the values.

public class Sample {
	public static void main(String args[]){
		
		
		for (int i = 0 ; i<getNames().length;i++){
			String a[] = new String[getNames().length];
			System.out.println(a[0]);
		}
	}
	
	public static String[] getNames() {
		   String names[] = {"bob", "jim"};
		   return names;
		}
}

But when i ran the program, I've got the output:
null
null

Help. I can't figure it out. Thank you again.

Edited 6 Years Ago by letlet_pogs: Oh. i've figured it out. ^_^

Hello. I am trying to return an array and print the values.

public static void main(String args[]){
		for (int i = 0 ; i<getNames().length;i++){
			String a[] = new String[getNames().length];
			System.out.println(a[0]);
		}
	}

Help. I can't figure it out. Thank you again.

The problem is with the main method. You're creating a new array of the same length as that of the one in the "getNames()" method. No need to do that. When you call the "getNames()" method, you will automatically get a reference to the array, which itself can be used to print the contents of the array.

Change the main method as shown below

public static void main(String[] args){
           for(String str : getNames())
                System.out.println(str);
}
This question has already been answered. Start a new discussion instead.