0

Not passing by reference

public class MyClass { public static void main(String[ ] args) { String s = new String("hello"); change(s);//not passing by reference System.out.println(s); } static void change(String foo) { foo = "hi"; } }

12th Feb 2017, 2:57 PM
rahat bhambri
rahat bhambri - avatar
4 odpowiedzi
+ 11
It IS passing. But you should know, that every time you assing value - reference is switching to another block of memory. So you dont touch passed block. To change it you should change the value directly. Use built-in 'Mutable' types for that purpose
12th Feb 2017, 3:15 PM
WittyBit
WittyBit - avatar
+ 9
Man, if you will say pointer1 = pointer2 It will NOT change the value on pointer1, it will just update the pointer variable
12th Feb 2017, 3:57 PM
WittyBit
WittyBit - avatar
+ 1
Java is a Object Oriented Pass by Value language. If you want to access the String s within the same class you'll need to change its scope. public class MyClass{ static String s; public static void main(String[ ] args) { s = new String("hello"); change(); System.out.println(s); } static void change() { s = "hi"; } } Also as mentioned Strings are not mutable. If you want to create an String Object and be able to change its value, use the StringBuilder or StringBuffer (thread safe) class. public class MyClass{ public static void main(String[ ] args) { StringBuilder s = new StringBuilder("hello"); change(s); // pass by value a copy of the object and its references System.out.println(s); } static void change(StringBuilder s) { s.replace(0, s.length(), "hi"); } }
12th Feb 2017, 11:53 PM
ChaoticDawg
ChaoticDawg - avatar
0
what do you mean by another block of memory , when reference is passed ie string foo =&s. it should change its value ,but it is not doing so
12th Feb 2017, 3:54 PM
rahat bhambri
rahat bhambri - avatar