This snippet prints ?!
String str = "";
str = str.replace(new StringBuilder('Z'), new StringBuilder("?!"));
System.out.println(str); // prints ?!
How come?
(I'm running JSE RTE 1.8.0_66 with HotSpot x64 VM (25.66-b18) on Win7)
This snippet prints ?!
String str = "";
str = str.replace(new StringBuilder('Z'), new StringBuilder("?!"));
System.out.println(str); // prints ?!
How come?
(I'm running JSE RTE 1.8.0_66 with HotSpot x64 VM (25.66-b18) on Win7)
After some digging I finally found the answer.
Contrary to the suggested explanation by resueman, the test
"".equals(new StringBuilder('Z'))
returns false, so I was NOT "effectively doing" "".replace("", "?!")
. To appreciate my point better, observe that"_".replace("", "^")
returns ^_^ . Do find a minute to run this LOC, you'll be amused, I'm sure.
The real reason behind this seemingly odd behaviour is that the regex engine matches boundaries in empty strings...