1
0

Strings in Java

Strings 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. The string is probably the most commonly used class in Java’s class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is an object of the type String. Even string constants are String objects. For example, in the statement

System.out.println("This is a String, too");

The string “This is a String, too” is a String constant. Fortunately, Java handles String constants in the same way that other computer languages handle “normal” strings, so you don’t have to worry about this.

The second thing to understand about strings is that objects of the type String are immutable; once a String object is created, its contents cannot be altered. While this may seem like a serious restriction, it is not, for two reasons:

  1. If you need to change a string, you can always create a new one that contains the modifications.
  2. Java defines a peer class of String, called StringBuffer, which allows strings to be altered, so all of the normal string manipulations are still available in Java.

String Constructors #

Strings can be constructed in a variety of ways. The easiest is to use a statement like this:

String firstString = "this is a test";

Once you have created a String object, you can use it anywhere that a string is allowed. For example, this statement displays firstString:

System.out.println(firstString);

You can also construct String objects explicitly using new. The String class supports the following simple constructors. public String(), Constructs a new String with the value “” an empty string.

public String(String value), Constructs a new String that is a copy of the specified String object value. This is a copy constructor. Because String objects are immutable, this is rarely used.

For Example:

String emptyString=new String();
String firstString=new String("this is a test");

Java defines one operator for String objects: +. It is used to concatenate two strings. For example, this statement

String firstString = "I" + " like " + "Java.";

results in firstString containing “I like Java.”

The following program demonstrates the preceding concepts:

Program to Demonstrate the usage of Strings.

class StringDemo
{
    public static void main(String args[])
    {
        String str1= "Java is a Pure Object Oriented Language";
        String str2 = "How do you find this Programming Language?";
        String str3 = str1 + " and " + str2;
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}
Java is a Pure Object Oriented Language
How do you find this Programming Language?
Java is a Pure Object Oriented Language and How do you find this Programming Language?

String Methods #

The String class contains several methods that you can use. Here are a few. You can test two strings for equality by using equals(). You can obtain the length of a string by calling the length() method. You can obtain the character at a specified index within a string by calling charAt(). The general forms of these three methods are shown here:

boolean equals(String object)
int length()
char charAt(int index)

Here is a program that demonstrates these methods:

Program to Demonstrate some String class methods.

class StringDemo2
{
    public static void main(String args[])
    {
        String str1 = "First String";
        String str2 = "Second String";
        String str3 = str1;
        System.out.println("Length of str1: " + str1.length());
        System.out.println("Char at index 3 in str1: " + str1.charAt(3));
        if(str1.equals(str2))
            System.out.println("str1 == str2");
        else
            System.out.println("str1 != str2");
        if(str1.equals(str3))
            System.out.println("str1 == str3");
        else
            System.out.println("str1 != str3");
    }
}

This program generates the following output:

Length of str1: 12
Char at index 3 in str1: s
str1 != str2
str1 == str3

Of course, you can have arrays of strings, just like you can have arrays of any other type of object. For example:

Program to demonstrate String arrays.

class StringDemo3
{
    public static void main(String args[])
    {
        String str[] = {"one", "two", "three"};
        for(int i=0; i<str.length; i++)
            System.out.println("str[" + i + "]: " + str[i]);
    }
}

Here is the output from this program:

str[0]: one
str[1]: two
str[2]: three

Some commonly used String Methods

The String class defines a number of methods that allows us to accomplish a variety of string manipulation. We have already discussed three methods in above program i.e. equals(), length() and charAt().

Others are as follows:

To convert a string str1 to lowercase str2=str1.toLowerCase();
To convert a string str1 to uppercase str2=str1.toUpperCase();
To replace all ‘x’ with ‘y’ in str1 str2=str1.replace(‘x’, ‘y’);
To remove white spaces at the beginning and end of the string str1 str2=str1.trim();
To compare str1 with str2, which returns 0 if str1 == st2 and +ve value if str1 > str2 and -ve if str1 < str2 str1.compareTo(str2)
To join two strings together i.e. str1 and str2 str3=str1.concat(str2)
To generate substring of str1 starting from mth character str2=str1.substring(m)
To generate substring of str1 starting from mth character to nth character (not including nth character) str2=str1.substring(m,n)
Return the index of the first occurrence of character x in string s1 int n=s1.indexOf(‘x’)
Returns the index of character x in the string s1 after pth position int n=s1.indexOf(‘x’,p)
Convert to String object a simple data value p String.valueOf(p)

Program to demonstrate the use of String methods.

class StringTest
{
    public static void main(String args[])
    {
        String s1 = new String("Java is a simple language");
        String s2 = new String("Developed by Sun Microsystem");
        String s3;
        s3 = s2.toLowerCase();  // convert to lower case
        System.out.println(s3);
        s3 = s1.toUpperCase();  // convert to upper case
        System.out.println(s3);
        s3 = s1 + s2;   // concatenate strings
        System.out.println(s3);
        int n = s1.indexOf('s');    // find index of first occurance 's'
        System.out.println("s is present at " + n);
        int m = s1.indexOf('s', n+1);   // find index of second occurance of 's'
        System.out.println("Second s is present at " + m);
        n = s1.indexOf('p');
        System.out.println("p is present at " + n);
        s3 = s1.substring(m);   // generate substring starting from location m
        System.out.println(s3);
        s3 = s1.substring(m, m+5);  // generate substring of 5 characters
        // starting from location m
        System.out.println(s3);
        char ch = s1.charAt(3); // find character at index 3
        System.out.println("Char at 3 = " + ch);
    }
}

Output:

developed by sun microsystem
JAVA IS A SIMPLE LANGUAGE
Java is a simple languageDeveloped by Sun Microsystem
s is present at 6
Second s is present at 10
p is present at 13
simple language
simpl
Char at 3 = a

String Arrays #

We can create an array of strings just like other arrays of objects. Each array location is a reference to a String object. String array can be initialized at declaration time or by using for loop after declaration.

In the following program, we have taken the array of strings that contain different names. The array is declared, created, and initialized using the statement:

String name[]={"Rajesh","Amit", "Praveen", "Mohan","Ankush", "Babita"};

The following statement can be used to declare a String array object:

String[] array1;

To create an array of size 10 (say) we can use the new operator to allocate memory as:

array1 = new String[10];

These two steps can be combined in a single statement to declare and create an array as:

String array1[] = new String[10];

We can assign the strings to the array1, element by element more efficiently using for loop.

Program Sorting the names of your friend using the Bubble-sort method in case of strings

class names
{
    public static void main(String s[])
    {
        String temp = null;
        String name[] = {"Rajesh", "Amit", "Praveen", "Mohan", "Ankush", "Babita"};
        int len = name.length;
        System.out.println("\nName of friends before sorting...\n");
        for(int i=0; i<len; i++)
        {
            System.out.println(name[i]);
        }
        for(int i=0; i<len; i++)
        {
            for(int j=i+1; j<len; j++)
            {
                if(name[i].compareTo(name[j]) > 0)
                {
                    temp = name[i];
                    name[i] = name[j];
                    name[j] = temp;
                }
            }
        }
        System.out.println("\n\nFriends in alphabetical order...\n");
        for(int i=0; i<len; i++)
        {
            System.out.println(name[i]);
        }
    }
}

The output of the above program is as follows:

Name of friends before sorting...
RajeshAmit
Praveen
Mohan
Ankush
Babita


Friends in alphabetical order...

Amit
Ankush
Babita
MohanPraveen
Rajesh

StringBuffer Class #

To create a variable-length string in your program, the StringBuffer class helps, which is a peer class of the String class. As compared to String, which creates a fixed length string but StringBuffer class creates a variable length string i.e. we can modify it in terms of length and content. We can insert characters and substrings in the middle of a string or append another string to the end. Some of the commonly used methods for StringBuffer class are:

StringBuffer();         // Constructor
StringBuffer(String);   // Constructor
str1.charAt(n);         // return character at nth position
str1.length();          // return length of string buffer
str1.setCharAt(n,'a');  // Modifies the nth character by 'a'
str1.append(str2);      // Appends str2 and str1 at the end
str1.insert(m,str2);    // Insert str2 at mth position in str1
str1.setLength(m);      // Modifies length of String str1 to m
str1.toString();        // Convert to STring object

StringBuffer object can use all the methods defined above in the String class.

Program to demonstrate the usage of StringBuffer class

class Manipulation
{
    public static void main(String s[])
    {
        StringBuffer str1 = new StringBuffer("Java is platform independent language");
        System.out.println("Original String: " + str1);
        int len = str1.length();
        System.out.println("Length of the above string: " + len);
        String str2 = new String(" Hello ");
        str1.insert(12, str2);
        System.out.println("Modified string " + str1);
        str1.setCharAt(5,'-');
        System.out.println("Modified string " + str1);
        str1.append(str2);
        System.out.println("Modified string " + str1);
    }
}

The output of the above program is as follows:

Original String: Java is platform independent languageLength of the above string: 37
Modified string Java is plat Hello form independent language
Modified string Java -s plat Hello form independent language
Modified string Java -s plat Hello form independent language Hello 

Leave a Reply