I want to replace a entire String with new value using String replaceAll method in Java
java
Solution
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.
Problem
``` String x = "Welcome to Java World"; System.out.println(x.replaceAll(".*","JAVA")); Actual Output = "JAVAJAVA" . Excepted Output = "JAVA". ``` Can anybody help why it replace like this . ".*" all characters in a original string and replace this with "JAVA" . Why this returns "JAVAJAVA" .