String and related classes

From Knowledge Kitchen
Jump to navigation Jump to search

String class

Strings are immutable. Want to modify a String? Make a new one!

Creating new String objects

There are many operators and expressions that could create a new String objects in code, e.g.:

  • "foo"
  • "fo" + "o"
  • new String('foo')
  • new String(char[] {'f', 'o', 'o'});
  • string1.concat(string2)
  • string1.substring(startIndex, endIndex)
  • string1.toUpperCase()
  • string1.toLowerCase()
  • string1.trim()
  • string1.replace(search, replace)

Searching for substrings

  • string1.indexOf(string2, startingIndex)
  • string1.contains(string2)

Finding out whats's inside a String

  • string1.length()
  • string1.charAt(index)
  • string1.indexOf(search)

Comparing two String objects

  • ==
  • string1.equals(string2)
  • string1.equalsIgnoreCase(string2)
  • string1.startsWith(string2)
  • string1.endsWith(string2)

Converting between types

  • string1.toCharArray()
  • String.valueOf(char[] {'f', 'o', 'o'})

Formatting String values

  • String.format(template, data,...)

Character class

The Character class is used to do more advanced processing and analysis of char primitives.

Comparing chars

  • character1.equals(character2)
  • character1.charValue() //the char primitive wrapped by the Character object
  • Character.isDigit(character1)
  • Character.isLetter(character1)
  • Character.isLetterOrDigit(character1)
  • Character.isLowerCase(character1)
  • Character.isUpperCase(character1)
  • Character.toUpperCase(character1)
  • Character.toLowerCase(character1)

StringBuilder class

StringBuilder is a wrapper class for String that provides useful methods for manipulating String values.

Creating a new StringBuilder object

  • new StringBuilder()
  • new StringBuilder(string1)

Finding out information about a StringBuilder

  • builder1.length()
  • builder1.capacity()

Mutator methods to modify the String encapsulated within the StringBuilder

  • builder1.append(string1)
  • builder1.delete(startIndex, endIndex)
  • builder1.insert(index, data)
  • builder1.replace(startIndex, endIndex, string1)
  • builder1.reverse()
  • builder1.trimToSize

Creating a regular String from a StringBuilder

  • builder1.toString()
  • builder1.substring(startIndex, endIndex)

Example programs

public class BasicString {
	public static void doIt(String s) {
		s = "bar";
	public static void main(String[] args) {
		//exampes of constructors
		String a = "foo";
		String b = new String("foo");

		//create a string from a character array
		char[] myChars = {'f', 'o', 'b'};
		String c = new String(myChars);
		//examples of getting string objects in other ways
		String d = "   foo   ".trim();
		String e = "foo bar".substring(0, 3);
		//output these examples
		System.out.println("These are each different ways of creating Strings");
		//example of passing a variable
		System.out.println("Java is a "pass by value" language - all arguments are passed by values, including reference types where the value is a memory address (i.e. a reference):");

		//changing case, by making a new string
		System.out.println("New strings, in either uppercase or lowercase, are easy to make from existing strings");
		String f = a.toUpperCase();
		String g = e.toLowerCase();

		//search and replace
		System.out.println("New strings can be made with a simple search and replace of an existing string.");
		String h = "this is an example string".replace(" ", "");
		//metadata about the string
		System.out.println("Some metadata about a given string");
		System.out.println("The string, g, is " + g.length() + " characters long");
		System.out.println("The 3rd character in g is " + g.charAt(2));
		System.out.println("The last character in g is " + g.charAt(g.length()-1));

		//find position of first "s"
		int pos1 = g.indexOf("s");
		//find the position of the second "s"
		int pos2 = g.indexOf("s", pos1+1);
		System.out.println("The index of the first occurance of the letter s is " + pos1);
		System.out.println("The index of the second occurance of the letter s is " + pos2);

		//the best, most reliable way to compare the values of two strings



public class CharacterExample {

	public static void main(String[] args) {

		//compare two char values
		char x = 'b';
		char y = 'b';
		if (x == y) {
			System.out.println("The two chars are the same!");

		//compare two Character objects
		Character a = new Character('b');
		Character b = new Character('b');
		if (a.equals(b)) {
			System.out.println("The two Characters are the same!");
		char c = a.charValue();
		System.out.println("The char inside the Character is " + c);


public class StringBuilderExample {

	public static void main(String[] args) {
		//the String primitive data type is immutable, and does not allow modifications once created.
		String b = "foo";
		String c = b + " bar"; //you must create a new String object if you want to make changes

		StringBuilder a = new StringBuilder("foo");
		//append to the existing string
		a.append(" bar");		
		//delete a single char from string

		//delete a range of charsf from string
		a.delete(0, 3);
		//replace some text with new text
		a.replace(0, 3, "abcdefghijklmnopqrstuvwxyz");
		//flip it in reverse
		//insert new data into string
		a.insert(5, " hello world! ");


What links here