Categories
interview

Java Objects, Arrays – Pass by Reference?

The array reference here is passed by value to the methods below. This is similar to what we usually see in case of Javascript.

Arrays

class createArr {
 int[] bag;

 public createArr(int[] arr) {
  this.bag = arr;
  this.addOne(arr);
 }

 public void addOne(int[] arr) {
  arr[0] = 1;
 }

 public void print() {
  System.out.println(this.bag[0]);
 }
}

public class HelloWorld {
 public static void main(String[] args) {
  int[] demo = {
   2
  };
  createArr cr = new createArr(demo);
  cr.print(); // 1
  System.out.println(demo[0]); // 1
 }
}

Objects

The following program to print kth last element in a linkedlist, demonstrates that value of method parameters always take values only. In the case of objects, the value (a copy) of the object reference is passed.

class Node {
 public String value;
 public Node next;

 public Node(String value) {
  this.value = value;
 }
}

public class LL {
 public static void main(String[] args) {
  Node a = new Node("First");
  Node b = new Node("Second");
  Node c = new Node("Third");
  Node d = new Node("Fourth");
  Node e = new Node("Fifth");

  a.next = b;
  b.next = c;
  c.next = d;
  d.next = e;

  kthToLast(2, a);
 }

 public static void kthToLast(int k, Node head) {

  Node p1 = getkth(k, head);
  System.out.println(head.next.value); // Second
  /* Here head value didn't change as mathod parameters only take values
     and so here the value of object reference was only passed */
  Node p2 = head;

  while (p1.next != null) {
   p1 = p1.next;
   p2 = p2.next;
  }

  System.out.println(p2.value); // Fourth
 }

 public static Node getkth(int k, Node head) {
  // Node curr = head;
  for (int i = 1; i < k; i++) {
   //curr = curr.next;  
   head = head.next;

  }
  //return curr;
  return head;
 }
}