0

I am trying to change the value of a final String variable to "#mango" without re-assignment, preferably by using StringBuffer and StringBuilder:

public static void main(String[] args) {
String finaal = "i am #apple";

//Case 1: Apache Commons Lang 3
StringUtils.replace(finaal, "#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" but actual "i am #apple" 

//Case 2 : 
finaal.replace("#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" actual "i am  #mango" but need re-assignment here 

}

djCode
  • 13
  • 3
  • 2
    You can't - strings are immutable. What's wrong with `finaal = finaal.replace("#apple", "#mango")`? – assylias Mar 29 '16 at 10:40
  • 1
    Possible duplicate of [String not replacing characters](http://stackoverflow.com/questions/12734721/string-not-replacing-characters) – Andreas Fester Mar 29 '16 at 10:47
  • sonar issue : Introduce a new variable instead of reusing the parameter – djCode Mar 29 '16 at 10:51
  • If you want to have different String in finaal, you need to reassign this. No way. You can try this StringBuilder sbuilder = new StringBuilder("#apple"); sbuilder.replace(0, sbuilder.length(), "#mango"); System.out.println(sbuilder.toString()); – Sarker Mar 29 '16 at 10:58

1 Answers1

1

Strings are immutable, the result of the replace is returned from the replace method. If you want to do a replace without re-assign you need to wrap your string in another class.

public static void main (String[] args) {
    StringHolder stringHolder = new StringHolder("#apple");
    stringHolder.replace("#apple", "#mango");
    System.out.println(stringHolder);
}


private static class StringHolder {
    private String str;

    public StringHolder(String str) {
        this.str = str;
    }

    public void replace(String from, String to) {
        String newStr = str.replace(from, to);
        this.str = newStr;
    }

    public String toString() {
        return str;
    }
}