Skip to Content

Java String Replace Example

  1. /*
  2. Java String replace example.
  3. This Java String Replace example describes how replace method of java String class
  4. can be used to replace character or substring can be replaced by new one.
  5. */
  6.  
  7. public class JavaStringReplaceExample{
  8.  
  9.   public static void main(String args[]){
  10.  
  11.     /*
  12.     Java String class defines three methods to replace character or substring from
  13.     the given Java String object.
  14.     1) String replace(int oldChar, int newChar)
  15.     This method replaces a specified character with new character and returns a
  16.     new string object.
  17.     2) String replaceFirst(String regularExpression, String newString)
  18.     Replaces the first substring of this string that matches the given regular
  19.     expression with the given new string.
  20.     3) String replaceAll(String regex, String replacement)
  21.     Replaces the each substring of this string that matches the
  22.     given regular expression with the given new string.
  23.     */
  24.    
  25.     String str="Replace Region";
  26.    
  27.     /*
  28.     Replaces all occourances of given character with new one and returns new
  29.     String object.
  30.     */
  31.     System.out.println( str.replace( 'R','A' ) );
  32.    
  33.     /*
  34.     Replaces only first occourances of given String with new one and
  35.     returns new String object.
  36.     */
  37.     System.out.println( str.replaceFirst("Re", "Ra") );
  38.    
  39.     /*
  40.     Replaces all occourances of given String with new one and returns
  41.     new String object.
  42.     */
  43.     System.out.println( str.replaceAll("Re", "Ra") );
  44.  
  45.   }
  46.  
  47. }
  48.  
  49. /*
  50.  
  51. OUTPUT of the above given Java String Replace Example would be :
  52.  
  53. Aeplace Aegion
  54. Raplace Region
  55. Raplace Ragion
  56.  
  57. */