Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Arrays in Java [duplicate]

Tags:

java

arrays

This time I want to print an array from the end to the start.

This is what I wrote:

public class Arrays {
public static void main (String[] args){
    for (int i = args.length; i >=0; i--){
        System.out.print(args[i]+" ");
    }
}

and this is the error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Assignment02Q04.main(Assignment02Q04.java:5).

Still having a hard time to realize the Eclipse error notifactions. I'll be glad for assistance.

like image 378
Unknown user Avatar asked Aug 15 '26 08:08

Unknown user


2 Answers

In java arrays start with 0. So an array of length 5 has elements with index 0 to 4

The following statement

for (int i = args.length; i >=0; i--)

loops from 5 to 0 (for an array of size 5)

Change it to

for (int i = args.length-1; i >=0; i--)

and bingo!

PS: Actually you did loop till 0, so you probably already knew that arrays start at 0.

like image 151
Nivas Avatar answered Aug 16 '26 20:08

Nivas


Java uses 0 indexing for arrays, so your args.length needs to take that into account; you should start at one before:

for (int i = args.length-1; i >=0; i--){
like image 27
kvista Avatar answered Aug 16 '26 21:08

kvista