What is the difference between replace and replaceAll in Java?

UPDATED: 04 February 2015

People out there have misconception about replace and replaceAll. I was having random discussion with my colleague he said replace is used to replace first occurrence of Character/String in String and replaceAll used to replace all occurrence of Character/String in String.

For those who has misconception about replace and replaceAll
replace: It will replace all occurrence of Character/String matched in String. replace can't process Regular Expression.
replaceAll: It will replace all occurrence of Character/String matched in String. replaceAll can process Regular Expression.

Source Code
public class ReplaceExample {
    public static void main(String[] args) {
        String str = "@aa @bx @ca @ax";
        System.out.println("Original String: "+str);
        System.out.println("------------------------");
        
        /* replace '@a' with 's' */
        System.out.println("replace: "+str.replace("@a", "s"));
        
        /* replace can't process REGULAR EXPRESSION */
        System.out.println("replace(with regexp): "+str.replace("@[a-z]*", "s"));
        
        /**
         * replaceAll can process REGULAR EXPRESSION
         * Replace any String followed by '@'
         */
        System.out.println("replaceAll: "+str.replaceAll("@[a-z]*", "s"));
    }
}

Output
Original String: @aa @bx @ca @ax
------------------------
replace: sa @bx @ca sx
replace(with regexp): @aa @bx @ca @ax
replaceAll: s s s s

0 comments :