0

Android 2.3.3

This is my code...

String[] expression = {""}; //globally declared as empty

somewhere in the code below, I am trying to assign a string to it.

expression[0] = "Hi";

I keep getting the following error...
12-08 22:12:19.063: E/AndroidRuntime(405): java.lang.ArrayIndexOutOfBoundsException

Can someone help me with this.. Can we access the index 0, directly as i am doing?

Actual Code :::

static int x = 0; // global declaration
String[] assembledArray = {""}; // global declaration

assembleArray(strSubString, expression.charAt(i)); //Passing string to the method

//Method Implementation
private void assembleArray(String strSubString, char charAt) {
        // TODO Auto-generated method stub

        assembledArray[x] = strSubString;
        assembledArray[x+1] = String.valueOf(charAt);
        x = x+2;

    }
4
  • 1
    Working fine for me: ideone.com/WERQ3H... can you please show the full code from creation to modification? Commented Dec 8, 2012 at 16:51
  • @Eric ::: Edited the question with code.. Commented Dec 8, 2012 at 16:57
  • @Bhavik Ambani ::: It is used to increment the array index. At first it will be zero and as the array builds up, x will help in accessing the array indexes Commented Dec 8, 2012 at 16:59
  • String[] expression = {""}; must be: String[] expression = new String[]{""}; Commented Mar 25, 2014 at 12:50

1 Answer 1

1

The problem is not in assembledArray[x]; it's in assembledArray[x+1].

At the first iteration, x+1 = 1, so you cannot access that part of the array. I would suggest using a dynamic array, aka an ArrayList:

ArrayList<String> assembledArray = new ArrayList<String>(); // global declaration

assembleArray(strSubString, expression.charAt(i)); //Passing string to the method

//Method Implementation
private void assembleArray(String strSubString, char charAt) {
    assembledArray.add(strSubString);
    assembledArray.add(String.valueOf(charAt));
}

This way, Java takes care of the resizing, and you don't need to keep track of x.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok.. But can you tell me, why I cannot access the index x+1?
Arrays do not resize themselves in Java. Your array is of length 1, so it only has index 0. When you attempt to access index 1, that is out of bounds (bounds are 0 to 0), so Java gives up and throws an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.