Broad Network


Passing Arrays to a Java Method

Java Just After the Basics – Part 4

Forward: In this part of the series, I talk about the modalities to respect, when passing arrays of known length and arrays of unknown length, to a Java method.

By: Chrysanthus Date Published: 2 Sep 2012

Introduction

This is part 4 of my series, Java Just After the Basics. In this part of the series, I talk about the modalities to respect, when passing arrays of known length and arrays of unknown length, to a Java method.

Passing Arrays of known Length
If you know the length of the array as argument, then the argument will be the name of the array and the parameter will be the declaration of an array with a different (parameter) name and without assignment. The following code illustrates this:

class Illustration
    {
        void myMthd(int[] para)
            {
                int inter0 = para[0];
                int inter1 = para[1];
                System.out.println(inter0);
                System.out.println(inter1);
            }
    }

class ArrArg
    {
        public static void main(String[] args)
            {
                int[] myArr = new int[2];
                myArr[0] = 10;
                myArr[1] = 20;

                Illustration obj = new Illustration();
                obj.myMthd(myArr);
            }
    }

In the main method, the first line declares the array with a length of 2. The next two lines assign values to the array elements. The line following instantiates the class of interest. The method of the class is called with just the array name as argument. In the parentheses of the method definition, for the corresponding parameter of the array, you start by typing the data type of the array. Immediately followed by open and close square brackets; then you type the name of the parameter. The name of the parameter now becomes the name of the array in the method definition (description). You use the parameter name in the method definition, in the same way that you use any array name outside. The rest of what is in the method definition should now be self-explanatory.

Array Length Unknown at Time of Method Definition Writing
It is possible for a program (application) to be written by two people. One man writes the class of interest and its method definition. The man writing the method definition does not know the length of the array. The other man writes the main method, and he knows the length of the array. The man writing the main method has no problem, nothing new to learn or worry about, and what he writes is similar to the main method above.

The problem is with the man writing the method definition. This is what he has to learn:

- The corresponding array parameter has to be the last parameter in the parameter list of the parentheses of the method definition. The argument correspondingly has to be last in the argument list.
- For this parameter, he begins by typing the data type, this time without square brackets. Following that he types three dots. Then he types the array parameter name. In this case, the last parameter is: dataType…paraName .
- Inside the method definition, before the array parameter name is used, he obtains the length of the array that has been sent with the expression: paraName.length . Having known the length of the array, he can now use the array parameter conveniently in the method definition. A typical use of this kind of thing in the method definition is in a loop.

The following example illustrates this:

class Illustration
    {
        void myMthd(boolean bool, char...para)
            {
                int len = para.length;
                for (int i=0; i<len; ++i)
                    {
                        System.out.println(para[i]);
                    }
            }
    }

class ArrArg1
    {
        public static void main(String[] args)
            {
                char[] myArr = new char[3];
                myArr[0] = 'A';
                myArr[1] = 'B';
                myArr[2] = 'C';

                Illustration obj = new Illustration();
                obj.myMthd(false, myArr);
            }
    }

Read and try the code. An expression such as, “char...para” in the parentheses and its length determining, “para.length” is known as a varargs. The construct (combination) enables you to use the elements of an array argument of un-predetermined length sent, in a method definition. In the method definition, the parameter represents the array.

Sequence of Arguments of Unknown Length
What about the case, when the designer of the method definition just knows that a sequence of arguments will be sent, but he does not know the number. He however, knows the particular type of arguments that will be sent. In this case, for the definition of the method, so far as parameters and length of sequence of arguments are concerned, the ellipse (…) parameter at the end of the parameter list, is still employed. The sequence of arguments correspondingly has to be at the end of the argument list. That is all the solution. Read and try the following code:

class Illustration
    {
        void myMthd(boolean bool, char...para)
            {
                int len = para.length;
                for (int i=0; i<len; ++i)
                    {
                        System.out.println(para[i]);
                    }
            }
    }

class ArrArg2
    {
        public static void main(String[] args)
            {
                char var0 = 'W';
                char var1 = 'X';
                char var2 = 'Y';
                char var3 = 'Z';

                Illustration obj = new Illustration();
                obj.myMthd(false, var0, var1, var2, var3);
            }
    }

In the main method, the sequence of arguments, “var0, var1, var2, var3”, are at the end of the argument list. There is no array in the main method as we had in the previous code.

An Array of Instantiated Objects
An array does not need to consist only of primitive object types. It can consist of instantiated object types as well. In this case, you normally would define (describe) a class, from which the instantiated objects are obtained. In the following code with array argument method call, the array consists of instantiated objects:

class FoArrCla
    {
        boolean bool;
    }

class Illustration
    {
        void myMthd(FoArrCla[] para)
            {
                boolean bu1 = para[0].bool;
                boolean bu2 = para[1].bool;

                System.out.println(bu1);
                System.out.println(bu2);
            }
    }

class ArrArg3
    {
        public static void main(String[] args)
            {
                FoArrCla ArrObj1 = new FoArrCla();
                ArrObj1.bool = true;
                FoArrCla ArrObj2 = new FoArrCla();
                ArrObj2.bool = false;

                FoArrCla[] myArr = new FoArrCla[2];

                myArr[0] = ArrObj1;
                myArr[1] = ArrObj2;

                Illustration obj2 = new Illustration();
                obj2.myMthd(myArr);
            }
    }

Read through the code noting how an array of instantiated objects has been created and assigned instantiated objects. Also note in the method definition block, how the array parameter name has used the dot to access the property of each object. In the parameter declaration in the parentheses, you begin with the class name for the objects in the array, then the open and close square brackets to indicate that you are receiving an array; and then the array parameter name. Try the code.

An Array of Strings
The String is actually a special class that the programmer does not need to define (describe). It is automatically available from the compiler for instantiation. A simple declaration is:

    String str;

where str is the object name. You can assign a string literal later. Again, you do not need to define the class; it has already been defined for you and is automatically available for you to use in the program (code). The following code is similar to the previous, but this time the objects are string objects. Read and try it:

class Illustration
    {
        void myMthd(String[] para)
            {
                String stri1 = para[0];
                String stri2 = para[1];

                System.out.println(stri1);
                System.out.println(stri2);
            }
    }

class ArrArg4
    {
        public static void main(String[] args)
            {
                String str1;
                str1 = "One AAA 111 aaa";
                String str2;
                str2 = "Two BBB 222 bbb";

                String[] myArr = new String[2];

                myArr[0] = str1;
                myArr[1] = str2;

                Illustration obj = new Illustration();
                obj.myMthd(myArr);
            }
    }

You can assign string literals to string array elements directly as in the segment:

                String[] myArr = new String[2];
                myArr[0] = "One AAA 111 aaa";
                myArr[1] = "Two BBB 222 bbb";

Array as Object and Referencing
The array is also a predefined class like the String class and is used automatically in code. However, the array defers from the way it is instantiated when compared to the string. When instantiating an array you use a new operator resulting in something like:

                FoArrCla[] myArr = new FoArrCla[2];

Contrast this with the short cut instantiation of a string, which is something like:

                String str1 = "One AAA 111 aaa";

Note the use of square brackets in the array instantiation statement.

Since the array is an instantiated object, if you pass it to a method, you are passing a reference and not a copy. In this case, any change of any array parameter element value is the same change in the array instantiated outside the method definition. In other words, the array in the method definition and the array outside are the same array. The following code illustrates this:

class FoArrCla
    {
        boolean bool;
    }

class Illustration
    {
        void myMthd(FoArrCla[] para)
            {
                para[0].bool = false;
                para[1].bool = true;

                System.out.println(para[0].bool);
                System.out.println(para[1].bool);
            }
    }

class ArrArg5
    {
        public static void main(String[] args)
            {
                FoArrCla ArrObj1 = new FoArrCla();
                ArrObj1.bool = true;
                FoArrCla ArrObj2 = new FoArrCla();
                ArrObj2.bool = false;

                FoArrCla[] myArr = new FoArrCla[2];

                myArr[0] = ArrObj1;
                myArr[1] = ArrObj2;

                Illustration obj2 = new Illustration();
                obj2.myMthd(myArr);

                System.out.println(myArr[0].bool); //changed
                System.out.println(myArr[1].bool); //changed
            }
    }

The print statements in the main method use the array name, myArr, and those in the method of interest, use the array name, para. The results are the same, reflecting the single change.

That is it for this part of the series. We stop here and continue in the next part of the series.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message