• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayIndexOutOfBound Exception  RSS feed

 
Dhivya rajagopal
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package HelloWorld;
public class Hellow {
String userName="dhivya";
public static void main(String args[])
{
Hellow h=new Hellow();
h.userName=args[0];
}
public void display( )
{

System.out.println("welcome"+userName);
}

}
If i run this in eclipse,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at HelloWorld.Hellow.main(Hellow.java:8)
is shown. can you please tell me the reason
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At this stage you are better off not using an IDE.

You need to pass a command-line argument if you wish to use args[0]. There is a tab on the run dialogue in Eclipse where you can write command-line arguments, but you are better off using the command-line directly:

java Hello Campbell

By the way: Give the userName field private access. Don't set it up with = but use the constructor to set it up.
Hello hw = new Hello(args[0]);
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And please UseCodeTags when posting code. It will highlight your code, making it much easier to read for everybody. You can edit your post with the button.
 
Kurosaki Ichigo
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dhivya rajagopal wrote:
is shown. can you please tell me the reason

you specified that you want to take in an argument using arg[0], so when you run the program, you must input an argument. do it from the command line, or setup your Eclipse environment to run with an argument. (but i suggest not using an IDE when learning how to program)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!