java String array

Posted on 2011-04-25
Medium Priority
Last Modified: 2012-05-11

I have the following code:

Outlink[] otherOutLinks;
otherOutLinks = new Outlink[0];
otherOutLinks[0]=new Outlink(link, "Next");

Why does the third line cause an exception?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

How can I fix it?

Question by:wsyy
  • 2
LVL 47

Assisted Solution

for_yan earned 248 total points
ID: 35461874
becaues when you say otherOutLinks = new Outlink[0];
you create array with zero elelemnts
nothing can go there
yyou eed at leas
otherOutLinks = new Outlink[1];
LVL 47

Expert Comment

ID: 35461885
This could  work:

Outlink[] otherOutLinks;
otherOutLinks = new Outlink[1];
otherOutLinks[0]=new Outlink(link, "Next");

LVL 92

Accepted Solution

objects earned 252 total points
ID: 35463544
Java arrays are zero-indexed, which means the first element is at index zero

> otherOutLinks = new Outlink[0];

You create an array with 0 elements

> otherOutLinks[0]=new Outlink(link, "Next");

Then you try and set the value of the first element
this fails because your array only has room for zero elements

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month15 days, 22 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question