Basic String methods

Method Purpose
concat(String) Concatenates one string onto another.
length() Returns the length of the string.
replace(char old, char new) Replaces all occurrences of old character with new character.
toLowerCase() Converts the entire string to lowercase.
toUpperCase() Converts the entire string to uppercase.
trim() Trims both leading and trailing whitespace from the string. It will remove the tabs (\t), carriage return (\r), new line (\n), and space characters at both ends of the string:

String Concatenation

Method Signature: public String concat(String s)

package com.ibytecode.strings.methods;
public class BasicStringMethods {
	public static void main(String[] args) {
		String name = "Java";
		System.out.println(name.concat(" Training"));

		/*name will refer to the old string since the concatenation
            	 operation is not assigned.*/
		/*to change name reference to refer to the new String object after
		 concatenation */
		name = name.concat(" Training");

		//+ operator for concatenation
		System.out.println("+ for Concatenation: " + name + " Training");

Java Training
Java Training
+ for Concatenation: Java Training Training

Length of a String

Method Signature: public int length()

String len = "";
System.out.println("Length = " + len.length());

Length = 20

length() is different from length array variable.
length() is a method in String class which returns length of the String whereas length is a public variable of array(that can be a String array too) to return the length/size of the array.

Replace characters in a String

Method Signature: public String replace(char oldChar, char newChar)

String old = "java";
System.out.println(old.replace('a', 'A'));
System.out.println("Old String: " + old);

Old String: java

Changing character case in a String

Method Signature:
public String toLowerCase()
public String toUpperCase()

String lowercase = "java training";
System.out.println("TO UPPERCASE: " + lowercase.toUpperCase());

String uppercase = "JAVA TRAINING";
System.out.println("to lowercase: " + uppercase.toLowerCase());

to lowercase: java training

Removing whitespaces from a String

To trim both leading and trailing whitespace from the string use trim() method.

Method Signature:
public String trim()

String whitespaces = "\t      java training    \r\n   ";

java training

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.