1

I am really confused how values are passed to a function. I am unable to figure out what types of values gets changed when we pass it to a function.

Example 1 - Passing a String(reference type) to a function -

public static String word = new String("Hello World");

public static void main(String[] args)
{
    System.out.println("Before: " + word);
    UpdateValue(word);
    System.out.println("After: " + word);
}

public static void UpdateValue(String x)
{
    x = "Hi World";
}

Output:

Before: Hello World
After: Hello World

Example 2 - Passing an array of String[] to the function -

public static String[] words = new String[] {"Hello", "Everyone"};

public static void main(String[] args)
{
    System.out.println("Before: " + Arrays.toString(words));
    UpdateValue(words);
    System.out.println("After: " + Arrays.toString(words));
}

public static void UpdateValue(String[] x)
{
    x[0] = "Hi";
}

Output:

Before: [Hello, Everyone]
After: [Hi, Everyone]

My questions -

  • How does it all work? String is a reference type, so my earlier assumption was that the value will be changed if we pass it to a function. But that didn't happen. The value did not change.
  • At the same time, when I passed the array (which is an object in Java, so basically a reference type?) we see that the original value got changed?
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Arpit Srivastava
  • 85
  • 1
  • 1
  • 6
  • In Java objects are passed by value, but the value is the reference to the object (arrays are objects too), in example 1 you are assigning the reference of a **different** object to the parameter, so given it is pass by value, the caller is not updated. In example 2, you are updating the reference **inside** the array, so the change is visible to the caller, because it is the **same** array it passed in. BTW: using `new String("Hello World")` is unnecessary and wasteful, and considered a bad practice. – Mark Rotteveel Jan 08 '21 at 08:17

1 Answers1

2

Both are passed as reference. The local variable in your methods point (initially) to the same object as the caller (main).

Here is what happens.

Strings are immutable. When you reassign the String in your method a new object is created and the local reference is updated to point to the new object. The original object still exists and the reference in main still points to it.

I’m the second example the reference to the array is copied on the same way. The local reference points to the same array as in main. But this time the array reference is not updated. Instead one string reference in the array is updated to point to a new string object.

DarkMatter
  • 1,007
  • 7
  • 13