Strings in Java VI: More String Methods

In this lesson we look at more string methods. We have already looked at some of the more interesting Java String’s methods and the intern() method. Here we will learn about a few more methods with examples.

Concatenating Java Strings

Concatenation is the act of joining two or more strings together. This is a fundamental operation and Java provides two ways of concatenating strings. You can use concat() method on one of the strings and pass the other string as an argument to this method. Alternately, you can use the ‘+‘ operator. Remember the ‘+‘ operator is specially overloaded for String. So, if you try to add a String to a non string object using ‘+‘ operator, the other object is converted to string using .toString() method and the concatenation in then performed. The concat() method on the other hand does the conversion by converting the String to StringBuilder and invoking the append method with the second String as the argument.

Either way, you will get an entirely new string. The code below demonstrates these two methods.

The output of the above code is

The trim() and replace() methods

The trim() method is frequently used String method. It removes all spaces from the beginning and end of a string. This method must be invoked on all inputs gathered from the user. For example, if you are asking your user’s internet banking password ( ? ! ) the user may enter extra spaces at beginning or end. Of course, a password with a trailing space is not the same as one without. Further, these spaces are not visible and therefore it makes debugging that much more harder. So, you should always run trim() on the strings gathered from external sources (e.g. users, other software, web etc.).

The replace() method, true to its name replaces a substring with the string provided as the parameter.

Here is an example of trim() method

The output of the above code is

Here is an example of replace() method

The output of this is –

Remember that replace() method has four overloaded variants. For more details, refer to the official JavaDoc.

Leave a comment

Your email address will not be published. Required fields are marked *