Take the 2-minute tour ×

In the following code

public class Test {

    public static void main(String[] args){
        int [] arr = new int[]{1,2};
        String b=new String("abc");


    public static void f(String b, int[] arr){

        arr[0] = 5;

Why the reference variable of the string doesn't behave like the reference variable of the array?.
I know string are immutable so operations on them creates new string but how about references to strings and how the reference b still refer to the old value although it was changed to refer to something else in f() method.

share|improve this question
References to strings do behave like other references. Try renaming the parameters of f to x and y and doing y = null; inside f, instead of arr[0]=5; and and you'll probably understand it. –  R. Martinho Fernandes Apr 13 '11 at 17:20
you have two different 'b' variables in your code, not just one. –  MeBigFatGuy Apr 13 '11 at 17:29

3 Answers 3

up vote 7 down vote accepted

Object references in Java are passed by value. Assigning just changes the value, it does not alter the original object reference.

In your example arr[0] is changed, but try arr=null and you will see it has no effect after the method has returned.

share|improve this answer

Method call is called by value in Java, well there is long debate about this , But I think that we should consider in terms of implementation language of Java which is C/C++. Object references just pointers to objects, and primitives are the values.. Whenever a method is called, actual arguments are copied to formal parameters. Therefore, if you change pointer to reference another object , original pointer is not affected by this change, but if you change object itself, calling party can also see the changes, because both party are referring the same object..

Well, in your example, you are changing string reference to null in called method, but you are changing object referred by array reference.. These two operations are not the same, therefore they do have different consequences.. for example, if you change the code as below, they would be semantically same operation..

arr = null;
share|improve this answer

You cnanot change the argument for any method, however you can do the following.

    String[] strings = {"Hello "};
    System.out.println("Using an array "+Arrays.toString(strings));

    StringBuilder text = new StringBuilder("Hello ");
    System.out.println("Using a StringBuilder '" + text+"'");

private static void addWorld(String[] strings) {
        strings[i] += "World!";
    strings = null; // doesn't do anything.

private static void addWorld(StringBuilder text) {
    text.append("World !!");
    text = null; // doesn't do anything.


Using an array [Hello World!]
Using a StringBuilder 'Hello World !!'
share|improve this answer

Your Answer


