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

By: Ivan Lim Viewed: 163877 times  Printer Friendly Format    


You can concatenate two strings using concat(), shown here:

String concat(String str)

This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example,

String s1 = "one";
String s2 = s1.concat("two");

puts the string "onetwo" into s2. It generates the same result as the following sequence:

String s1 = "one";
String s2 = s1 + "two";


The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,

String s = "Hello".replace('l', 'w');

puts the string "Hewwo" into s.


The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:

String trim( )

Here is an example:

String s = " Hello World ".trim();

This puts the string "Hello World" into s.

The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state's capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

// Using trim() to process commands.
class UseTrim {
public static void main(String args[])
throws IOException
// create a BufferedReader using
BufferedReader br = new
BufferedReader(new InputStreamReader(;
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial