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*/