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?