0

why can't I change a String variable's value by reference?

if Strings are object, why can't I change this String's value by reference(A) within another method? isn't "A" a reference type? A's output still is: "salar". how can I change that by reference? public class Program { public static void main(String[] args) { String A = "salar"; test(A); System.out.println(A); } public static void test(String b) { b = "Hello"; } } https://code.sololearn.com/c89Mq87kdNHj/?ref=app

15th Dec 2018, 11:11 PM
salar vahidi
salar vahidi - avatar
4 ответов
+ 2
String class objects are immutable i.e. it can't be changed once created Inside test(), a new object of type String is created Use the below statements to see the address System.identityHashCode(A); System.identityHashCode(b);
15th Dec 2018, 11:33 PM
Rishi Anand
Rishi Anand - avatar
+ 2
thanks Rishi now it makes sense but I don't know how to write those statements to see the address. I'm unfamiliar with them but I'm curious to see how it will show the address. I tried different ways but it shows errors. would you please write the complete syntax?
16th Dec 2018, 12:59 AM
salar vahidi
salar vahidi - avatar
+ 2
public class Program { public static void main(String[] args) { String A = "salar"; test(A); System.out.println(System.identityHashCode(A)); } public static void test(String b) { b = "Hello"; System.out.println(System.identityHashCode(b)); } }
16th Dec 2018, 9:22 AM
Rishi Anand
Rishi Anand - avatar
0
thank you so much 🙏😄
17th Dec 2018, 3:38 AM
salar vahidi
salar vahidi - avatar