Code
public class Foo {
public static void main(String[] args) {
//declaring and initializing String variable 'str' with value "outside"
String str = "main";
//declaring and initializing Array 'array' with values
String [] array = {"main"};
//printing values of str and array[0]
System.out.println("str : " + str + " , array[0] : " + array[0]);
//calling function foo()
foo(str, array);
//printing values after calling function foo()
System.out.println("str : " + str + " , array[0] : " + array[0]);
}
static void foo(String str, String[] array){
str = "foo";
array[0] = "foo";
}
}
Output
str : main , array[0] : main
str : main , array[0] : foo
Question
Why does the string str
remains same as "main" but the value of array[0]
gets modified from "main" to "foo" after calling the function foo()
? Shouldn't the effect be the same?