Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings are immutable then how the replace() works?

Tags:

java

string

I was trying to replace the first letter/char of a string by it's last one and last one by it's first one. E.g. abcd => dbca. Strings are immutable in Java then how can we explain the behavior of this program? Please have a look at final output. str1 has no char 'a' but in final output it appears unexpectedly.. how? //The argument of frontBack() is String "abcd".

 public static void frontBack(String str) {
   String first= ""+str.charAt(0);
   System.out.println("first char is "+first);
   String last = ""+str.charAt(str.length()-1);
   System.out.println("last char is "+last);
   String str1;
   str1 = str.replace(""+str.charAt(0),last);
   System.out.println("String str1 is => "+str1);
   String str2 ;
   str2 = str1.replace(""+str1.charAt(str1.length()-1),first);
   System.out.println("String str2 is derived from str1(dbcd) which has no 'a' but o/p is =>  "+str2);    
  }
 /* Have a look at output:
                        first char is a
                        last char is d
                        String str1 is => dbcd
                        String str2 is derived from str1 i.e. "dbcd" which has no 'a' in it but o/p is =>  abca*/
like image 751
Deepeshkumar Avatar asked Sep 05 '26 14:09

Deepeshkumar


1 Answers

Strings are immutable in Java then how can we explain the behavior of this program?

str1 = str.replace(""+str.charAt(0),last);

This method takes a String which is immutable and creates a new String which is immutable. Immutable doesn't mean the String cannot be created.

Note: if you want to manipulate some text you can use a StringBuilder which is mutable. You can create this from a String and you can create a new String from it. This is often, but not always used, sometimes a char[] is used directly for performance reasons.

the new string which is created has no char 'a' but in final output it appears unexpectedly.

This is where using a your debugger would help. You would see that

String first= ""+str.charAt(0); // first = "a"

and later when you do

str2 = str1.replace(""+str1.charAt(str1.length()-1),first);

this is the same as

str2 = str1.replace("d", "a");

so it should be no surprise that the ds are replaced by as

I am using replace() not replaceAll()

From the Javadoc for String.replace(CharSequence, CharSequence)

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

like image 75
Peter Lawrey Avatar answered Sep 08 '26 02:09

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!