Java Passing Arrays to Methods

Java Passing Arrays to Methods


Java Passing Arrays to Methods

Summary: It is allowed to pass arrays to methods like any other objects. Explained in simple terms in this tutorial "Java Passing Arrays to Methods". Here, pass-by-reference is also shown in Java style.

Sometimes, it is required to pass arrays to method parameters to transfer large amount of data between methods; instead of creating a global array which can be changed by every object. The concept used is Java passes "objects by reference" and not by value. Arrays, being predefined objects, pass by reference. Other way, a Java programmer can achieve pointer affect by passing objects between method calls.

Program on Pass-By-Reference using Java Passing Arrays to Methods

Java Passing Arrays to Methods

In the main() method, an integer array x is created with the elements, 10, 20 and 30. x[0] prints 10. So, nothing new so far.

To display() method an array object x is passed.

Observe, the method parameter is an array object, not a value. So, while passing, an array object should be passed as an argument to display() method. This is done with display(x).

Now, x and y array objects refer the same location that stores 10, 20 and 30 elements. Changing y elements also changes x elements because x and y refer the same location address.

Java Passing Arrays to Methods

Now x[0] prints 100 (not 10) as x array is also changed when y array changes its y[0] value to 100. Exactly pointer affect.

One more similar program is available where arrays are passed to constructors.

Pass-by-reference is also explained using StringBuffer object – StringBuffer Petty Methods and Pass-By-Reference.

Do you want to know?

2 thoughts on “Java Passing Arrays to Methods

  1. sunil

    I am new in java , I have a question that if object is important and all the work like accessing initialising is done by object ,then why we cant make the object of main class..? pls tell

Leave a Reply

Your email address will not be published. Required fields are marked *