Passing a string array as a parameter to a function java

Viewed 169609

I would like to pass a string array as a parameter to a function. Please look at the code below

String[] stringArray = {'a', 'b', 'c', 'd', 'e'};

functionFoo(stringArray);

Instead of:

functionFoo('a', 'b', 'c', 'd', 'e');

but if I do this I am getting an error stating that convert String[] into String. I would like to know if it is possible to pass the values like that or what is the correct way to do it.

8 Answers

please check the below code for more details


package FirstTestNgPackage;

import java.util.ArrayList;
import java.util.Arrays;


public class testingclass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        System.out.println("Hello");
        
        int size = 7;
        String myArray[] = new String[size];
        System.out.println("Enter elements of the array (Strings) :: ");
        for(int i=0; i<size; i++)
        {
        myArray[i] = "testing"+i;
        }
        System.out.println(Arrays.toString(myArray));
        
        
        ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
        
        
        System.out.println("Enter the element that is to be added:");
        
        myArray = myList.toArray(myArray);
        
        someFunction(myArray);
        }
    
    public static void someFunction(String[] strArray) 
    { 
        System.out.println("in function");
        System.out.println("in function length"+strArray.length );
        System.out.println(Arrays.toString(strArray));
        
           }
        }

just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...

Thank you

Related