Can anyone answer me please?
public class ReplaceString{
public static void main(String arg[]) {
String a = "Hariom";
a = a.replace('H', 'b');
System.out.println(a);
}
}
Can anyone answer me please?
public class ReplaceString{
public static void main(String arg[]) {
String a = "Hariom";
a = a.replace('H', 'b');
System.out.println(a);
}
}
A String
is immutable, which means you cannot change the string value on the same address. If you change it, it will create a new object and you have to assign it to the current string object. For example,
String a = "Hariom";
a.replace('H', 'b');
System.out.println(a); //will print "Hariom"
because a
is not changed. Instead, you created a new String
in memory with the value bariom
and to show that change to a
, you have to point the newly created string to a
, i.e.
a= a.replace('H', 'b');
Maybe this would be a bit more clear:
Step 1: String a = "Hariom";
you create a new string in memory and the variable a
points to it.
Step 2: a.replace('H', 'b');
if you replace some character in String
a
, a new String
is created in the heap with no variable pointing to it.
Step 3: a= a.replace('H', 'b');
if you call replace()
and assign it to the variable a
, what happens is that the new String
bariom
is created in the heap. Then you assign it to a
causing a
to point to the new String
.
change your code to :
public static void main(String arg[]) {
String a = "Hariom";
String b = a.replace('H', 'b'); // returns a new string instance
System.out.println(a==b); // prints false
}
b
and a
are different objects. immutable
means you cannot modify that object.
Note : Reflection can be used to break immutability of Strings.
a = a.replace('H', 'b');
This doesn't modify the String
a
, it returns a new String
instance (unless there is nothing to replace, in which case the original String
is returned).
According to Javadocs:
String#replace(char oldChar, char newChar)
method Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar
String a = "Hariom";
a = a.replace('H', 'b');
/* method returns new instance of String ("bariom")
and you referencing the new instance to variable a,
so now String object "Hariom" is no longer referenced by any variable
and is available for garbage collection.
*/
System.out.println(a);
The row
a.replace('H', 'b');
generate a new String. Then you set the a variable to the new value.
a.replace
does not modify a
, it returns a new String object. If you call a.replace
without reassigning to a
, you will notice that the original String has not changed.
Variables can contain immutable objects, but you are still able to reassign to them. Reassigning does not change the object, it only changes which object the variable refers to.