Why does function modify array[0] but not string in Java? -
this question has answer here:
code
public class foo { public static void main(string[] args) { //declaring , initializing string variable 'str' value "outside" string str = "main"; //declaring , initializing array 'array' values string [] array = {"main"}; //printing values of str , 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 string str
remains same "main" value of array[0]
gets modified "main" "foo" after calling function foo()
? shouldn't effect same?
no shouldn't, because of how java deals references.
you give method 2 parameters: string (that is, address string) , array (that is, address array). these addresses stored locally in str
, array
, if change addresses, addresses outside method (str
, array
of main()
) won't change.
then create string "foo" , assign (or rather, adress) local str
. won't have effect on str of main(). however, array address local, what's inside array not. if write
array = {"foo"};
that wouldn't affect array
of main()
,
array[0] = "foo";
you change inside array you've given reference.
Comments
Post a Comment