I believe this is a basic query and am missing something out. However am exasperated finding an answer to the issue and thus seek your guidance.

The intent is to create a static method generateStringArray() that can return an array. However whenever I run the code in the below form, it throws error:

Static method cannot be referenced from a non static context: List<String>

  1. My method is static and arrays can be returned from static
  2. Instead of string, if I use void and don't return, the compiler does run

Why is this throwing an error? What part of the code is being run as a class instance and not static? Does it have soemthing to do with the way I have defined the function or the string ?

I have checked at other solutions available for the similar issue but my query pertains to what is not static in the code?


public class test_clonestring {

    public static String[] generateStringArray (Integer lenstr){    
        String[] sstring = new String[lenstr]; 

        for (Integer i = 0; i<lenstr; i++) {
            sstring[i] = 'Test ' + i;


        return (sstring);

  • How to reproduce the error? Because this code works for me, test_clonestring.generateStringArray(2) and this runs without an error-
    – Raul
    Oct 4, 2017 at 10:43
  • The error occurs when one invokes: Alternate1 test_clonestring obj = new test_clonestring(); /* String[] sarray = */ obj.generateStringArray(5); Alternate2 test_clonestring obj = new test_clonestring(); String[] sarray = obj.generateStringArray(5);
    – max steel
    Oct 4, 2017 at 10:58

1 Answer 1


The code you have posted does compile. To call it you will need to use the class name like this (because the method is static):

String[] stringArray = test_clonestring.generateStringArray(5);

This will not compile:

String[] stringArray = new test_clonestring().generateStringArray(5);
  • heh Keith C. Thanks for the quick response. So if I do a void return; it is fine to use instance of the object. However when the static method does return like in this case String array, we cannot use an instance object to invoke the method. Is this correct ?
    – max steel
    Oct 4, 2017 at 10:53
  • @maxsteel The return type should make no difference. You may have made more than one change at a time...
    – Keith C
    Oct 4, 2017 at 11:02
  • Hi Keith, ok no worries. I will have a relook as to why the new instance is not working for the static again then. Thanks!
    – max steel
    Oct 4, 2017 at 11:05
  • @maxsteel in Java it is possible to call static methods from an instance (bad practice), but in apex it is not compiling. Oct 4, 2017 at 11:09
  • Hi @Alex, true that is a bad practice; however as part of my beginner learning; I was just trying all available ways to invoke and see if it works or not :)
    – max steel
    Oct 4, 2017 at 11:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .