Pages

Monday, November 1, 2010

By-ref and by-val passing in Java

On my last job-interview I answered wrong on this question: "Is the passing of arguments is held by value or by reference?". Here is a small example on this topic.

Actually if it is understood once, the one sentence to refresh it all is - All is passed by reference, primitives are passed by value. Of cause immutable objects could not be changed.
public static void main(String[] args) {

    int sampleInt = 1;
    doWithInt(sampleInt);
    System.out.println(sampleInt);

    int[] sampleArray = new int[3];
    for (int i = 0; i < sampleArray.length; i++) {
      sampleArray[i] = i;
    }
    printArray(sampleArray);
    doWithArray(sampleArray);
    printArray(sampleArray);

    String s = "Hello";
    doWithString(s);
    System.out.println(s);

    StringBuilder sampleStringBuilder = new StringBuilder("Hello");
    doWithStringBuilder(sampleStringBuilder);
    System.out.println(sampleStringBuilder);
  }

  private static void doWithInt(int sampleInt) {
    sampleInt++;
    System.out.println(sampleInt);

  }

  private static void doWithArray(int[] sampleArray) {
    for (int i = 0; i < sampleArray.length; i++) {
      sampleArray[i]++;
    }
    printArray(sampleArray);
  }

  private static void printArray(int[] sampleArray) {
    System.out.print("[");
    for (int i = 0; i < sampleArray.length; i++) {
      System.out.print(sampleArray[i] + ", ");
    }
    System.out.println("]");
  }

  private static void doWithString(String s) {
    s += " world!";
    System.out.println(s);
  }

  private static void doWithStringBuilder(StringBuilder sampleStringBuilder) {
    sampleStringBuilder.append(" world!");
    System.out.println(sampleStringBuilder);
  }


* This source code was highlighted with Source Code Highlighter.

Output of this code:

2
1
[0, 1, 2, ]
[1, 2, 3, ]
[1, 2, 3, ]
Hello world!
Hello
Hello world!
Hello world!

No comments:

Post a Comment