Your regular expression can match 0 to all characters. First, it matches the entire string "Welcome to Java World"
, then it matches the end of the string ""
, replacing both with "JAVA"
.
To make this work how you expect it, you have a couple options.
String x = "Welcome to Java World";
System.out.println(x.replaceAll(".+","JAVA"));
Notice the + instead of the *, this means 1 or many, so the end won't be matched.
or
String x = "Welcome to Java World";
System.out.println(x.replaceFirst(".*","JAVA"));
This will only replace the entire string with "JAVA"
, the empty end of the string won't be replaced.