-5

need to understand flow of following progarm. what should be the output? when i compile this program i got "ArrayIndexoutofBound" error.

public class test {

   public static void main(String args[]) { 

      Integer intObj=Integer.valueOf(args[args.length-1]);
      int i = intObj.intValue();

      if(args.length > 1) 
         System.out.println(i);
      if(args.length > 0)
         System.out.println(i - 1);
      else 
         System.out.println(i - 2);
   }
}
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Raxit
  • 11
  • 1
  • 3
    Easy to see how this would happen: args array doesn't have any values if you don't have command line arguments. – duffymo Oct 06 '14 at 13:28
  • Are you entering any [command-line arguments](http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html)? You'll get that exception if you don't have any. – TNT Oct 06 '14 at 13:28
  • Based on the error and the code, I think that you must provide at least 1 command line argument. The ArrayIndexOutOfBounds happens when you fail to do that. The program should run fine when you have provided one. – Zibadian Oct 06 '14 at 13:28
  • an empty array has length 0, and `args[-1]` is undefined. – Hunter McMillen Oct 06 '14 at 13:28
  • if I am passing args[] without any command line argument then by default size of array value will be 0 ?? – Raxit Oct 06 '14 at 21:23
  • @Raxit Yes, but in the amount of time it took for you to get a reply, you could have found out for yourself :P – Dennis Meng Oct 08 '14 at 04:10
  • :D thanks....keep that in mind..!! – Raxit Oct 08 '14 at 04:16

2 Answers2

0

"ArrayIndexoutofBound" :Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

So probably you are not passing any command line argument. So args.Lenght return 0.

So here :

Integer intObj=Integer.valueOf(args[0-1]);

Index is negative thats why JVM throw "ArrayIndexoutofBound"

Vikas Verma
  • 3,626
  • 6
  • 27
  • 40
  • Integer intObj=Integer.valueOf(args[10-1]); output : 9 with error arrayIndexOutOfBound. – Raxit Oct 06 '14 at 21:28
0

Add some input check if some input exist before Integer.valueOf(args[args.length-1]); And add some input information to execution.

Misha
  • 433
  • 4
  • 10