The program compiles but it gives the following error:
Two
One
Three
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at testingN.printArray(testingN.java:19)
at testingN.main(testingN.java:10)
I am really new into Java ( and programming ) and I'm stuck with this.
public class testingN
{
public static void main(String[] args)
{
String[] names = new String[3];
names[0] = "Two";
names[1] = "One";
names[2] = "Three";
printArray(names);
}
public static String printArray(String[] data)
{
int i;
for (i = 0; i < data.length; i++)
{
System.out.println(data[i]);
}
return data[i];
}
}
return data[i];is using index 3, becauseiis incremented before the loop exits.return data[i-1];. That said, a method that prints should be declared asvoid(not return anything). If you want to implement another functionality you should do it somewhere else...voidand take out the return statement.