Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

run time exception  RSS feed

 
satya narayan reddy
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class String2Int{
public static void main(String argv[]){
try{
int i= Integer.parseInt(argv[0]);
System.out.println("Coverted to int val = " + i);
}catch(NumberFormatException nfe){ System.out.println("Could not covert to int");
}
}
}

runtime exception:
------------------

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at String2Int.main(String2Int.java:7)


Hi all,
for the above program its generating the above runtime exception can anybody
fix the problem?

thanks,
satya
 
Campbell Ritchie
Marshal
Posts: 55707
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An . . . OutOfBoundsException usually occurs, in my opinion, because there is a mistake in the programming. Ditto NullPointerException and letting division by zero throw an ArithmeticException.

You have to make sure your array actually contains an element no 0 before you pass it . . .
 
Campbell Ritchie
Marshal
Posts: 55707
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I hadn't noticed you are in the main method; you ought not to have "real" code in the main method in the first place. If you are getting that sort of exception, it is because you have forgotten to pass a command-line argument.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your program expects a command line parameter, if you don't specify it when running the program the array argv will have length 0, so the first element (argv[0]) doesn't exist. Try running your program with the following command:

java String2Int 1234
 
satya narayan reddy
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jasper and campbell..the error got fixed
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!