Basic String methods

20 January 2012 By Nithya Vasudevan 1,110 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
MethodPurpose
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.*/
		System.out.println(name);
		/*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
Java Training
+ for Concatenation: Java Training Training

Length of a String

Method Signature: public int length()

String len = "theopentutorials.com";
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);

jAvA
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 UPPERCASE: JAVA TRAINING
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   ";
System.out.println(whitespaces.trim());

java training