concat(), replace(), and trim() Strings in Java.


The concat() method of the String class appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

Example

public class Test {
   public static void main(String args[]) {
      String s = "Strings are immutable";
      s = s.concat(" all the time");
      System.out.println(s);
   }
}

Output

Strings are immutable all the time

This replace() method of the String class returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Example

public class Test {
   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      System.out.print("Return Value :" );
      System.out.println(Str.replace('o', 'T'));
      System.out.print("Return Value :" );
      System.out.println(Str.replace('l', 'D'));
   }
}

Output

Return Value :WelcTme tT TutTrialspTint.cTm
Return Value :WeDcome to TutoriaDspoint.com

This trim() method of the String class returns a copy of the string, with leading and trailing whitespace omitted.

Example

import java.io.*;
public class Test {
   public static void main(String args[]) {
      String Str = new String(" Welcome to Tutorialspoint.com ");
      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}

Output

Return Value :Welcome to Tutorialspoint.com

Updated on: 26-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements