I need to store input from user in controller so it can be used for calculations.

To do this I am using an array, to get input in the controller.

But getting issue: Subscript is invalid because list is empty

I have tried initializing array in the controller in static block, controller and get section but getting the same issue.


    public with sharing class TestControllerForIssue{

  public String [] testArray{get; set;}

    public void doSomething(){
        System.debug('Started doSomething()');
        System.debug('testArray[0]=' + testArray[0]);

    public TestControllerForIssue(){
        testArray = new String[5];


Visualforce page:

<apex:page controller="TestControllerForIssue">
    <apex:form >
            <apex:commandButton value="CallAPI" action="{!doSomething}"/>
            <apex:pageBlock id="productData">   
                        <th style="text-align: center">Test Value</th>
                            <td><apex:inputText value="{!testArray[0]}"/></td>
  • Where/When do you receive this error? – Jayant Das May 13 at 13:22
  • I see it on the VF page when it is run on the Salesforce orf – वरुण May 13 at 14:12

You are getting that error because you have just initialized the array mentioning what should be the size of the array. Hence it will contain 5 null values, in order for you to use that array, you have to initialize the elements in the array.

In your controller's constructor, you have to add new instances of string, which then can be binded to visualforce page.

So your constructor would be

public TestControllerForIssue(){
    testArray = new List<String>{'','','','',''}
  • This is not completely correct. testArray = new String[5]; will initialize the array. It's still fine not to have a value in it. So if you access the element say testArray[3], it will give you null. – Jayant Das May 13 at 13:22
  • @Jayant Yup my bad, just observed it in the debug log, corrected it. Thanks for the observation. – Vijay Ganji May 13 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.