0

This code is written in notepad and run in the command prompt. The input is computer is fun, and the output is:

fun
is
computer

When I tried to write it in NetBeans, it gives me an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

What is the problem, and how can I get the same output as when I run it in the command prompt?

class A{
   public static void main(String[] args) {
    args[0]="Computer";
    args[1]="Science";
    args[2]="is";
    args[3]="fun";
      if (args.length>1)
      {
         String []newargs = new String [args.length-1];
         for (int i = 0 ; i<newargs.length ;i++)
         {
            newargs[i]=args[i+1];
         }

         main (newargs);
         //System.out.println(args.length);
      }
      System.out.println(args[0]);
      return;
   }
}
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 4
    "_when i tried to write it in netbeans it gives me an error_" What is the error? – takendarkk Feb 12 '20 at 14:48
  • 3
    Welcome to Stack Overflow. Even when you're writing code in Notepad, if you're asking others to read it later, it would really help if you'd indent it so make it readable. – Jon Skeet Feb 12 '20 at 14:49
  • Are you passing any arguments into the program? I notice you don't check for the case that `args.length ==0`, is args[0] set? – user27158 Feb 12 '20 at 14:56
  • You try to **assign** to the "incoming" args array. But that array represents the command line parameters **passed** to your JVM run. So, unless you provide at least 4 arguments, the first incoming args array has the wrong size. Note that you create your newargs with a specific size, but you seem to assume that the incoming args has a specific size ... because ... why? – GhostCat Feb 12 '20 at 15:07
  • Those assignments were originally commented out before the formatting was fixed. Not sure if they are uncommented when OP is receiving the error. From my perspective, if the Exception really is ArrayIndexOutOfBounds, then my answer below provides an explanation of why that is happening – loganrussell48 Feb 12 '20 at 15:20

1 Answers1

0

If the if-statement condition is true, you're calling main(newargs).

This is recursion: when a method calls itself.

The issue here is that the for loop iterates until i is equal to newargs.length-1 then, you try to access args[i+1] which is 1 index more than is available in the array.

This is because in Java, arrays are 0-indexed: An array of size 5 has indices 0-4. If you're trying to access an element at array.length, that will always be 1 more than is available!

Edit: So, to make this work, change the boundary condition on the for loop to be i<newargs.length-1 and you should no longer get ArrayIndexOutOfBoundsExceptions

loganrussell48
  • 1,656
  • 3
  • 15
  • 23