Way2Java

Pass Arrays Constructor Java

Pass Arrays Constructor: Sometimes, it is required to pass arrays to methods and constructors to transfer large amount of data between methods.
Following is the example on Pass Arrays Constructor
public class Publisher
{
  public Publisher(String faculty[])
  {
    for(int i = 0; i < faculty.length; i++)
    {
      System.out.println(faculty[i]);
    }
  }
  public static void main(String args[])
  {
    String teachers[] = { "Jyothi", "Jyostna", "Sumathi" };
    Publisher p1 = new Publisher(teachers);
  }
}

           
       String teachers[] = { "Jyothi", "Jyostna", "Sumathi" };
       Publisher p1 = new Publisher(teachers);

A teachers string array object is initialized and passed to Publisher constructor.

       public Publisher(String faculty[])
       {
         for(int i = 0; i < faculty.length; i++)
         {
           System.out.println(faculty[i]);
         }
       }

Now, Publisher constructor receives teachers array object in faculty array object. Now teachers and faculty refer the same location; The concept behind is in "Java objects are passed by reference". Infact, printing of faculty elements prints teachers. elements. The teachers and faculty objects refers or points to the same location. This is how Java achieves pass-by-reference without saying the word "pointers".

For a similar program, passing arrays to methods, refer Java Passing Arrays to Methods where Pass-by-reference affect in Java is shown.

So, now you know how Java supports pass-by-reference or call-by-reference. Java supports almost all but without talking the word pointers. Later in DS, you will come to know how to manage Linked list without pointers.

Pass your comments and suggestions on this tutorial "Pass Arrays Constructor Java".