Course Content‎ > ‎Session 4‎ > ‎

Strings

String manipulation is the most common part of many Java programs.  Strings represent a sequence of characters.  The easiest way to represent a sequence of characters in Java is by using a character array. 

For example,
 
    char charArray[ ] = new char [4];
    charArray[0] = 'J';
    charArray[1] = 'a';
    charArray[2] = 'v';
    charArray[3] = 'a';

Although character arrays have the advantage of being able to query their length, they themselves are not good enough to support the range of operations we may like to perform on strings. In Java, strings are class objects and implemented using two classes, namely String and StringBuffer. A Java string is an instantiated object of the String class.  In Java, strings are declared and created as follows:
 
    String stringname;
    Stringname = new String("string");

Here  are few other examples,
 
    String firstName;
    firstName = new String("John");

Or,

    String firstName = new String("John");  

To find the length of the string, you can use the length method of the String class. For example,
 
    int m = firstName.length();

Java strings can be concatenated using the + operator.
 
    /* firstName and lastName are Java strings containing string constants */
    String fullName = firstName + lastName; 
    String city1 = "New" + "York";
    System.out.println (firstName + "Richardson");

String Arrays

We can also create and use arrays that contain strings. This statement will create an itemArray of size 3 to hold three string constants. To assign the strings to itemArray, either a for loop can be used or strings can be assigned elements by using three independent statements.
 
    String itemArray[ ]=new String[3];
    itemArray[0] = "Pencils";
    itemArray[1] = "Paint";
    itemArray[2] = "KeyBoards";  

String Methods

The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. Given below is a list, which shows some of the most commonly used String methods and their descriptions:
 
    1. toLowerCase
    Converts the string s1 to lowercase
    s2 = s1.toLowerCase();
    
    2. toUpperCase
    Converts the string s1 to uppercase
    s2 = s1.toUpperCase();
     
    3. replace
    Replaces all instances of x with y
    s2 = s1.replace(‘x’, ‘y’);
     
    4. trim
    Removes white spaces at the beginning and end of the string s1
    s2 = s1.trim( );
     
    5. equals
    Returns true if s1 is equal to s2.  
    s1.equals(s2);
     
    6. equalsIgnoreCase
    Returns true if s1 = s2, ignoring the case of characters
    s1.equalsIgnoreCase(s2);
     
    7. length
    Returns the length of s1
    s1.length();
     
    8. charAt
    Returns the character at the nth position of the string s1. The first character is at index 0.
    s1.charAt(n);
     
    9. compareTo
    Returns negative value if s1 < s2, positive if s1 > s2 and 0 if s1 = s2
    s1.compareTo(s2);
     
    10. concat
    Concatenates s1 and s2 and resultant string is assigned to s3
    s3 = s1.concat(s2);
     
    11. substring
    Returns substring starting from nth character
    s1.substring(n)
     
    12. valueOf
    Creates a String object of the parameter p, which may be a simple type or an object.
    String.valueOf(p);
     
    13. toString
    Creates a string representation of the object p
    p.toString( );
     
    14. indexOf
    Returns the position of the first occurrence of 'x' in the String s1.
    s1.indexOf('x');
     
    Returns the position of 'x' that occurs after nth position in the string s1
    s1.indexOf('x',n);
     
    15. valueOf
    Converts the parameter value to string representation.
    String.valueOf(Variable);

Given below is an example in which the strings in the array country are sorted and displayed in ascending order:

    class stringSort
    {
        public static void main(String args[])
        {
            String country[] = {"NewYork", "Delhi", "Tokyo", "London", "Amsterdam"};
            int i,j,size;
            size = country.length;
            String temp = null;
             
            /* the array is sorted in the ascending order */
            for(i = 0; i < size; i++)
            {
                for(j = i+1; j < size; j++)
                {
                    if(country[i].compareTo(country[j]) > 0))  
                    {
                        temp = country[i];
                        country[i] = country[j];
                        country[j] = temp;
                    }
                }
            } 
            
            /* the sorted array is displayed */
            for(i = 0; i < size; i++)
            {
                System.out.println(country[i]);
            }
        }
    }  

Comments