-1

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)

Igor Soudakevitch
  • 671
  • 10
  • 19
  • 1
    What do you think it should print and why? That little bit of information shows us you've done your research. – Sotirios Delimanolis Oct 19 '16 at 15:07
  • @SotiriosDelimanolis Since the object didn't contain the target sequence Z, it shouldn't have changed --- that was my initial reasoning. Apparently faulty, and now I know why :) I'm just studying for my OCP cert exam and need to play with code, that's all... Cheers – Igor Soudakevitch Oct 20 '16 at 06:30

1 Answers1

0

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...

Igor Soudakevitch
  • 671
  • 10
  • 19