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.

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);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.