The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Strings

A string is a sequence of characters. In Java, strings are objects of String class. This class provides methods for string manipulation. We can create a string object using a string literal or new keyword.

String str = "csegeek"; // create a string object using a literal
String str = new String("csegeek"); // usual way of instantiating class

In Java, String objects are immutable i.e once created, strings cannot be modified. In order to create modifiable strings, Java provides StringBuffer class which is discussed later in this module.

Methods of String Class
Following table shows a list of commonly used methods of String class.

MethodDescription
char charAt(int index)Returns the character at a specified index.
String concat(String str)Appends the specified string to the end of this string.
boolean equals(Object ob)Compares this string to the specified string.
boolean equalsIgnoreCase(String str)Compares this string to the specified string ignoring case.
int compareTo(String str)Lexicographic comparison of two strings.
int compareToIgnoreCase(String str)Lexicographic comparison ignoring case.
String toUpperCase()Convert this string to uppercase string.
String toLowerCase()Convert this string to lowercase string.
int length()Returns the length of this string.
String substring(int start_index)Returns a new string which is a substring of this string with specified start index.
String substring(int start_index, int end_index)Returns a new string which is a substring of this string with specified start index and end index.
boolean startsWith(String prefix)Find if a string starts with a specified prefix.
boolean endsWith(String suffix)Find if a string ends with a specified suffix.
String trim()Returns a copy of this string with leading and trailing whitespaces removed.

Following program illustrates the use of methods of String class :

public class StringDemo {
   public static void main(String args[]) {
      String str = "csegeek";
      int size = str.length();
      System.out.println("Size of " + str + " is " + size);
      String ustr = str.toUpperCase();
      System.out.println("String in uppercase : " + ustr);
      boolean eq = str.equalsIgnoreCase(ustr);
      if ( eq == true )
         System.out.println("Strings are same ( case ignored )");
      else
         System.out.println("Strings are not same");
      String substr = str.substring(2, 6);
      System.out.println("Substring : " + substr);
      char ch = str.charAt(4);
      System.out.println("Character at index 4 is " + ch);
      String newstr = str.concat(ustr);
      System.out.println("Strings after concatenation : " + newstr);
   }
}


Array of Strings
Similar to any other array of objects, we can create an array of objects. See the program below :

public class StringArrayDemo {
   public static void main(String args[]) {
      // create and initialize an array of String objects
      String arr[] = { "Anjali", "Rahul", "Tina", "Aman" };
      String arr1[] = new String[2]; // create the String array
      arr1[0] = "csegeek"; arr1[1] = "website"; // initialize
      for (int i = 0; i < arr.length; i++) { // print arr elements
         System.out.print(arr[i] + " ");
      }
      System.out.println();
      for (String obstr : arr1) { // print arr1 elements
         System.out.println(obstr);
      }
   }
}


StringBuffer Class
The StringBuffer class is used to create mutable ( modifiable ) string. StringBuffer is preferred over String when we expect modification operations ( append, insert, delete ) on strings. Some of the commonly used methods of StringBuffer class are shown in the table below :

MethodDescription
setCharAt(int index, char ch)Replace the character at a particular index with the specified character.
setLength(int n)Set the length of StringBuffer.
length()Returns the length of the StringBuffer.
insert(int index, char ch)Insert a character at specified index of the StringBuffer.
append(String str)Append the specified string to the StringBuffer.
delete(int start, int end)Delete the characters of the substring in a StringBuffer.
replace(int start, int end, String str)Replace the substring of a StringBuffer with the specified string.
reverse()Reverse the character sequence of StringBuffer.
capacity()Returns the current capacity of StringBuffer.

Following program illustrates the use StringBuffer class :

public class StringBufferDemo {
   public static void main(String args[]) {
      StringBuffer strbuf = new StringBuffer("csegeek");
      System.out.println("StringBuffer : " + strbuf);
      System.out.println("Length of the string : " + strbuf.length());
      strbuf.setCharAt(0, 'C');
      strbuf.append("com");
      System.out.println("Modified string : " + strbuf);
      strbuf.insert(7, '.');
      System.out.println("Now the string is : " + strbuf);
      strbuf.reverse();
      System.out.println("After reversing : " + strbuf);
      strbuf.delete(3, 6);
      System.out.println("After deleting substring : " + strbuf);
   }
}


StringTokenizer Class
The StringTokenizer class is used to break a string into tokens. Following program illustrates the use of StringTokenizer class :

import java.util.*;
public class StringTokenizerDemo {
   public static void main(String args[]) {
      StringTokenizer strtok = new StringTokenizer("This is csegeek");
      while(strtok.hasMoreTokens()) {
         System.out.println(strtok.nextToken());
      }
   }
}

Back | Next