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
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);
+ 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?
+ 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));
}
}
0
thank you so much 🙏😄