Please disable adblock to view this page.

← Go home

Passing Arguments in Java

java-display

May 1, 2017
Published By : Pratik Kataria
Categorised in:

Passing Values to Methods

  • Passing to a method by copy
    • The method receives a copy of variable.
  • Passing to a method by reference.
    • The method receives a reference to the original object.
    • That is, any changes made to the object within the method will be reflected outside the method
  • In Java, variables are always passed by copy

Passing Primitive Values

void incValue( int i ) {
    i++;
    System.out.println("Inside method values of i is: " +i);
}

int iOriginal = 10;
System.out.println("iOriginal before: " +iOriginal);
incValue(iOriginal);
System.out.println("Original after: " +iOriginal);

After running the above pseudo code we find that:

  • Original before: 10
  • Inside method value of i is: 11
  • Original after: 10

So, pass by copy.

Primitives Wrapped in Objects

void incValue( int[] i ) {
    i[0]++;
    System.out.println("Inside method: " +i[0]);
}

int[] iArrOriginal = {10, 20, 30);
System.out.println("iArrOriginal before: " +iArrOriginal[0]);
incValue(iArrOriginal);
System.out.println("iArrOriginal after: " +iArrOriginal[0]);

After running the above pseudo code we find that:

  • iArrOriginal before: 10
  • Inside method: 11
  • iArrOriginal after: 11

So, even though we are passing a copy of array. The new copy of array references the original values that are stored outside method.

Object Variables are References

  • A reference variable points to a location in memory.
  • When a variable is passed to a function, a new reference is always created.
  • However, both references (outside method and inside method) point to the original objects or values.

Strings are complex objects, then what if we pass String?

We’ll find that the change in String will not be reflected outside the method.

Why?

Because Strings are immutable!

Pratik Kataria is a budding programmer, web designer and developer.