[Java] How to Pass a Primitive-Type Variable by Reference and to Change its Value in the Method in Java?

In Java, it doesn’t use pointer for representing the variables. The primitive type of variable is used to store a value. For example,

  int varInt = 1;

The varInt variable is store the integer value “1”.

When we use the new operation to create a object, the return value is a reference of object.

  Object varObj = new Object();

The varObj references to an Object-type instance.

If we want to pass an object to a method, we will write down this code,

void Med_1() {
 Object varObj = new Object();
 Med_2(varObj);
}

void Med_2(Object obj) {
 obj.setValue(2);
}

Because the obj is also a reference to the Object-type instance, so we can call the setValue method, and then this will effect to the Object-type instance.

But, when we want to pass the primitive-type variable by reference and you want to change its value in the method. For this case, you can follow this example,

public class JavaTestProject {
 public static void med1(int[] a) {
  a[0] = 2;
 }
 public static void main(String[] args) {
  int[] varInt = { 1 };
  med1(varInt);
  System.out.println(varInt[0]);
 }
}

The result prints on console. You can find out the a[0]’s value is 2.

Otherwise, you can also create a Pool class for storing these primitive-type variables for doing pass-by-reference.

The Pool class example (You can find this code from Google Android – Gallery),

public final class Pool<E extends Objects> {
 private final E[] mFreeList;
 private int mFreeListIndex;
 public Pool(E[] objects) {
  mFreeList = objects;
  mFreeListIndex = objects.length;
 }
 public E create() {
  int index = --mFreeListIndex;
  if (index >= 0 && index < mFreeList.length) {
   E object = mFreeList[index];
   mFreeList[index] = null;
   return object;
  }
  return null;
 }
 public void delete(E object) {
  int index = mFreeListIndex;
  if (index >= 0 && index < mFreeList.length) {
   mFreeList[index] = object;
   mFreeListIndex++;
  }
 }
}

發佈留言