[java] Passing a string array as a parameter to a function java

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.

This question is related to java function arrays

The answer is


Feel free to use this how ever you like.

/*
 * The extendStrArray() method will takes a number "n" and
 * a String Array "strArray" and will return a new array
 * containing 'n' new positions. This new returned array
 * can then be assigned to a new array, or the existing
 * one to "extend" it, it contain the old value in the 
 * new array with the addition n empty positions.
 */
private String[] extendStrArray(int n, String[] strArray){
    String[] old_str_array = strArray;
    String[] new_str_array = new String[(old_str_array.length + n)];
    for(int i = 0; i < old_str_array.length; i++ ){
        new_str_array[i] = old_str_array[i];
    }//end for loop

    return new_str_array;

}//end extendStrArray()

Basically I would use it like this:

String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.

I believe this should be the way this is done...

public void function(String [] array){
....
}

And the calling will be done like...

public void test(){
    String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
    function(stringArray);
}

look at familiar main method which takes string array as param


I think you forget to register the parameter as String[]


More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.

private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}

All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.

There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-

 String concat (String ... strings)
   {
      StringBuilder sb = new StringBuilder ();
      for (int i = 0; i &lt; strings.length; i++)
           sb.append (strings [i]);
      return sb.toString ();
   }

Here we can call the function like concat(a,b,c,d) or any number of params you want.

More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?