Yesterday I was working on customized letters and memos. And I have made mapping keywords, like: [Dateofbirth], [Email], [Employee], [Salary] etc, which will be replace at the time of generation.
Example: dear [Employee], your Current Salary is [Salary].
expected output:
Output: dear John, your Current Salary is 12000.
I am using replaceAll() method here is a code.
String str = "dear [Employee], your Current Salary is [Salary].";
Map<String,String> vals = new HashMap<String,String>();
vals.put("[Employee]","John");
vals.put("[Salary]","12000");
for(String key:vals.keySet()){
str=str.replaceAll(key,vals.get(key));
}
System.out.println(str);
but the out is:
dJohn1200012000 [JohnJohnJohnJohnJohnJohnJohnJohn], JohnJohnu12000 Cu1200012000Johnnt 1200012000John1200012000John is [1200012000John1200012000John].
I was confused and Googled it and tried to make it correct, after that I changed replaceAll() with replace()
EX: str=str.replace(key,vals.get(key));
Now it is working fine. The question is Why replace all is doing such kind of behavior what is the core concept of replaceAll() and When to use replace() when to use replaceAll().
Thanks