-4

Here is the problem description:

in my preparation for ocjp test, I have encountered a problem, and I can not figure out what's wrong with it.

package test;
class Test005{
    public static void main(String[] args){

      //Integer i = args[0];//cannot convert string to Integer
        Integer I = Integer.valueOf(args[0]); // Error ArrayOutOfBoundsException :0
        int j = 12;
        System.out.println(j == i);

    }
}

the first Integer I = args[0] is wrong, because the args[0] is a string, while the I is a int; however, the second Ineteger I = Integer.valueOf(args[0]) complies smoothly, but the JVM throw an error, and I just cannot figure it why?

Jens
  • 67,715
  • 15
  • 98
  • 113
qiwen li
  • 11
  • 2

3 Answers3

0

To run this you have to pass arguments while running the program which will be assigned to args[0], then your program will work fine. If you are using an IDE like eclipse you can pass arguments through Arguments tab. Check below link to see how you can pass arguments in eclipse IDE : http://www.cs.colostate.edu/helpdocs/eclipseCommLineArgs.html

arpit garg
  • 61
  • 5
0

JVM throws ArrayOutOfBoundsException because your args is empty which mean you didn't pass any arguments when running this program. Try to run this command: java Test005 45. By the way, I think you should check some more cases for example: args[0] is not a number format ("ab", "a1") or when args is empty.

Phi Luu
  • 192
  • 4
0

The big issue you are not spotting is the fact that

Integer I = Integer.valueOf(args[0]);

will work if and only if:

  • args array hat AT LEAST ONE element

AND

  • args[0] is something you can convert into an Integer object

in your case the fisrt condition is never met, so you are trying to get the 1st element of an empty array, therfore the Exception

you didnt mention how are you testing that, are you calling that method from another class/how, or are you starting the app from a terminal/how...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97