Search code examples
javaarraysstatic-methods

Use Array Initializers in a Function in Java


I want to write a function which gives me a different int array testArray as an output according to the input I choose. In this example, I want to choose number = 0, and get testArray = {1,2,3,4,5} as a result. When I give testArray values, I get this error:

Array constants can only be used in initializers

public class ArrayExample{  
    
    public static void main(String args[]){
        int number = 0;
        int[] newArray = new int[5];
        newArray = getValues(number);
    }
    

    public static int[] getValues(int number) {
        
        int[] testArray = new int[5];
            
            if(number == 0) {
                testArray  = {1,2,3,4,5}; 
            }
            else if(number == 1) {
                testArray  = {2,3,4,5,6}; 
            }
            else if(number == 2) {
                testArray  = {3,4,5,6,7}; 
            }
            else if(number == 3) {
                testArray  = {4,5,6,7,8}; 
            }       
            else{
                testArray  = {5,6,7,8,9}; 
            }   

            
        return testArray;
    }

    
}

Solution

  • We cannot assign values to an array using the following syntax.

    int[] newArray = new int[5];
    testArray  = {1,2,3,4,5}; 
    
    

    To solve the issue you can use

      testArray  = new int[] {1,2,3,4,5};