One of the most commonly used Java classes is String. This is because string handling is an integral part of many Java programs. The string class is packaged in Java. Lang. Thus, it is automatically available to all programs. Java implements String as objects of type String. Implementing strings as objects allows Java to provide full complement of features that make string handling convenient.

String class implements the following interface:

  • Comparable<String>
  • CharSequence
  • Serializable

The Comparable interface specifies how objects are compared. CharSequence defines a set of methods that are applicable to a character sequence. Serializable simply indicates that the state of a String can be saved and stored using Java’s serialization mechanism.

The String Constructor: The String class supports a large number of constructors. To create an empty String, we call the default constructor. For example,

String str = new String ();

This will create an instance of String with no characters in it.

To create a String initialized by an array of character, we use following constructor.

String str = new String (char[] ch);

We can specify a sub range of a character array as an initializer using the flowing constructor:

String str = new String (char[] ch, int startIndex, int numChars);

When constructing a String from an array, the contents of the array are copied into the String.

Three String Related Language Features

Because strings are a common and important part of programming. Java supports three especially useful string features directly within the syntax of the language. These are the automatic creating of new String instances from string literals, concatenation of multiple String objects of the + operator and the conversion of other data types to a string representation.

String Literals : String literal is created by specifying a quoted string. For each string literal in our program, Java automatically constructs a String object. Thus, we can use a string literal to initialize a String object. For example:

String str = “This is an example of string literal”;

String Concatenation: In general, java does not allow operations on String objects through operators. One exception to this rule is the + operator, which concatenates two strings, producing a String object as result. This allows us to chain to together a series of + operations. For example, the following fragment concatenates three strings:

String age = “19”;

String str = “He is “+age+”years old”;

System.out.println(str);

This displays the string ” He is 19 years old”;

String Concatenation with Other Data Types

We can concatenate strings with other types of data. For example, consider the following code.

int age = 10;

String str = “He is”+age+”years old.”;

System.out.println (str);

In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representations as a String object. The string is then concatenated as before. The compiler will convert an operand of the + is an instance of String.

Overloading toString()

When Java converts an object into its string representation during concatenation, it does so by calling the object’s toString() method. As we know that every class implements toString () because it is defined by Object. It has this general form:

String toString()

It returns a string that describes the object. When overriding toString() for our class, simply return a String object that contains human readable string that approximately describes an object of your class. By overriding toString() for classes that you create , you allow them to be fully integrated into Java’s programming environment.

Consider the following program.

class Box{

    public double length;

    public double height;

    public double depth;

    public Box(double l, double h, double d){

        length = l;

        height = h;

        depth = d;      

    }

    public String toString(){

        return "Dimensions are "+length+ " by "+depth+" by "+height+".";

    }

}

public class OverrideToString {

    public static void main(String[] args) {

        Box b = new Box(10,12,14);

        System.out.println (b);

    }  

}

 

The output of the above program is:

run:

Dimensions are 12.0 by 14.0 by 12.0.

The length () Method

Since strings are not arrays, they do not have a length field. However, String does not have a method called length () that returns the length of a string. A string’s length is the number of characters that it contains. The length method is shown here.

For example:

String str = “Theta”;

System.out.println (str.length ());

Displays 5, because there are five characters in str.

Character Extraction

The String class provides three ways in which characters can be obtained from a String object. Each is examined here. Although the characters that comprise a string cannot be indexed as if they were a character array, a number of String methods employ an index. Like arrays, string indices begin at zero.

charAt()

To obtain a single character from a String. We can use the charAt () method. It has this general form:

char charAt(int where)

Here, where is the index of the character that we want to obtain. The value of where must be nonnegative and specify a location within the string. The charAt () method returns the character at the specified location. The following program shows charAt () in action. It is used to display a string using double spacing.

Let us consider the following program.

public class ChatAtAndLength {

    public static void main(String[] args) {

        String str = "Programming is not art and science";

        for(int i=0;i<str.length();i++)

            System.out.println (str.charAt (i)+ " ");

    }   

}

 

The output of the above program:

In the program, the length () is used to control the number of iterations and charAt () is used to obtain each character in sequence.

getChars () : If you need to obtain more than one character at a time, you use the getChars() method. It has this general form:

void getChars(int source, int sourceEnd, char [] target, int targetStart)

Here, sourceStart specifies the index of the beginning of the substring to obtain, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd-1. The array that will receive the characters is specified by target. The index within target array is large enough to hold the number of characters in the specified substring.

Consider the following program

public class GetCharsDemo {

    public static void main(String[] args) {

   String str = "programming is both art and science";

   int start = 15;

   int end = 23;

   char[] buf = new char[end-start];

   str.getChars(start, end, buf, 0);

   System.out.println(buf);

}   

}

 

The output of the above program is:

Run:

both art

toCharArray()

If we want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray(). It returns an array of characters for the entire string. It has this general form:

char[] toCharArray()

For example, here is how to obtain an array that contains the entire contents of str:

String str = “Programming is both art and science.”;

char[] chrs = str.toCharArray();

System.out.println (chrs);

After this sequence executes, chrs will contain the characters that were in str. and the println () statement will display.

Programming is both art and science

String Comparison

To compare two strings for equality, use equals (). It has this general form:

boolean equals (Object str)

Here, str is the object being compared with the invoking String object. This method is specified by Object and overridden by String. The equals () returns true if the strings contain the same characters in the same order. It returns false if the strings differ or if str is not a String. The comparison is case sensitive.

To perform a case insensitive comparison, call equalIgnoreCase(). When it compares two strings, it considers A-Z to the same as a-z for example. It has this general form:

boolean equalIgnoreCase(String str)

Here, str is the String object being compared with the invoking String object. It returns true if, independent of case differences, the strings contain the same characters in the same order, and false otherwise.

public class EqualityDemo {

    public static void main(String[] args) {

        String str1 = "table";

        String str2 = "table";

        String str3 = "TABLE";

        if(str1.equals(str2))

            System.out.println(str1 +" equals "+str2);

        else

            System.out.println(str1 +" does not equals"+str2);

        if(str1.equals(str3))

            System.out.println(str1 +" equals"+str3);

        else

            System.out.println(str1 +" does not equals "+str3);

        if(str1.equalsIgnoreCase(str3))

            System.out.println(str1 +" equals "+str3);

        else

            System.out.println(str1 +" does not equals "+str2);

    }   

}

 

The output of the above program is:

Run:

table equals table

table does not equals TABLE

table equals TABLE

Equals () Versus ==

Before moving on, it is important to emphasize that the equals () method and the == operator perform two different operations. The equals () method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. Thus, they perform two fundamentally different operations. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal.

Consider the following program:

public class EqualsNotEqualTo {

public static void main(String[] args) {

   String str1 = "Alpha";

   String str2 = new String(str1);

    System.out.println (str1+" equals "+str2+" is "+str1.equals (str2));

    System.out.println (str1+ " == "+str2+ " is "+(str1==str2));

}   

}

 

The output of the above program is:

Run:

Alpha equals Alpha is true

Alpha == Alpha is false

The variable str1 refers to the String instance created by the Literal “Alpha“. The object referred to by str2 is created with str1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct. This means that str1 and str2 do not refer to the same objects and are, therefore, not == as shown by the programs’ output.

The regionMatches()

The regionMatches() method compares a subset (that is a region) of a string with a subset of another string. There is an overloaded form that allows us to ignore case in such comparions. Here are the general forms for these two methods.

boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars);

boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars);

For both versions, startIndex specifies the index at which the region to campare begins within the invoking String object. The String being compared is specified by str2. The index at which the comparison will start within str2 is specified by str2StartIndex. The length of the region being compared is placed in numChars. The first version is case sensitive. In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is significant.

Consider the following example:

public class CompareRegions {

public static void main(String[] args){

    String str1 = "Standing at river's edge.";

    String str2 = "Running at river's edge";

    if(str1.regionMatches(9, str2, 8, 12))

    System.out.println("Regions match");

    if(!str1.regionMatches(0, str2, 0, 12))

    System.out.println("Regions do not match");

}   

}

 

The output of the above program is:

Run:

Regions match

Regions do not match

 

StartsWith () and endsWith ()

String defines two methods that are, more or less, specialized forms of regionMatches (). The startWith () method determines whether a given String begins with a specialized string. Conversely, endsWith() determines whether the String in question ends with a specialized string. They have the following general forms:

boolean startsWith (String str);

boolean endsWith (string str);

Here, str is the string being tested. In the case of startWith(), if str matches the beginning of the invoking string, true is returned. In the case of endsWith() , if str matches the end of the invoking string, true is returned. Otherwise, both methods return false on a mismatch. The comparisons are case sensitive.

Let us consider the following example:

String str = “Status: Complete”;

Then the following two expressions are true:

str.startWith (“Status”)

and

str.endsWith (“Complete”)

Obtaining a Modified String

As explained, String objects are immutable. It is however, still easy to obtain a modified version of a String through the use of one or more methods defined by String. These methods return a modified copy of the original string. Because the original string is never modified, the rule of immutability is not violated. Here we will look at substring (), replace (), and trim (), all of which return modified versions of the string on which they are invoked.

substring (): We can obtain a string by use of substring (). It has two forms. The first is:

String substring (int startIndex)

Here, startIndex specifies the index at which the desired substring will begin. This form returns a copy of the substring that begins at startIndex and includes the remainder of the invoking string.

The second form of substring () allows you to specify both the beginning and ending index of the substring. It takes following form:

String substring (int startIndex, int endIndex)

public class UseSubStrings {

    public static void main(String[] args) {

        String original = "This is a test. This is too";

        String start;

        String end;

        start =original.substring(5);

        end = original.substring(5, 12);

        System.out.println("The original string is : "+original);

        System.out.println("The first substring is  : "+start);

        System.out.println("The second substring is : "+end);

    }   

}

 

The output of above program is:

Run:

The original string is : This is a test. This is too

The first substring is  : is a test. This is too

The second substring is : is a te

replace(): The replace() method has two forms. The first form replaces one character with another through a string. it  has the following general form:

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The modified copy of the invoking string is returned.

The second form of replace () replaces one character sequence with another throughout a string. It has this general form:

String replace(CharSeqeunece, Charsequnence replacement)

The sequences can be objects of type String, because String implements the Character interface. The modified copy of the invoking string is returned.

Let us consider the following program.

public class Replace {

public static void main(String[] args) {

    String orgStr = "Alpha beta gamma alpha beta gamma ";

    String result;

    System.out.println("Original string:"+orgStr);

    result = orgStr.replace('g', 'x');

    System.out.println("The modified string is"+result);

}   

}

 

The output of the above program is:

Run:

Original string: Alpha beta gamma alpha beta gamma

The modified string is Alpha beta xamma alpha beta xamma

trim () : The trim() method deletes leading and trailing whitespaces (typically, spaces, tabs, and newline characters) from a string. It has the following general form:

If he invoking string has leading and /or trailing whitespaces, then trim() removes the whitespaces and returns a new string that contains the result. Otherwise, the resulting string is simply equivalent to the invoking string.

Here is an example. Given the string:

String str = ”  gamma  “;

After

 str = str.trim();

str will contain only string “gamma”. The leading and trailing whitespaces has been deleted.

The trim() method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state’s capital. It uses trim() to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

import java.io.*;

public class UseTrim {

    public static void main(String[] args)throws IOException{

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String str;

       System.out.println("Enter stop to quit");

        System.out.println("Enter name of state");

        do{

            str = br.readLine();

            str = str.trim();

            if(str.equals("Illonois"))

                System.out.println("Capital is Springfield");

            else if(str.equals("Missouri"))

                System.out.println("Capital is Jefferson city");

            else if(str.equals("California"))

                System.out.println("Capital is Sacramento");

            else if(str.equals("Washinton"))

                System.out.println("Capital is Olympia");       

    }while(!str.equals("stop"));   

    }

}

 

When this program is run, if the user enters something like ” Illinois  “, the call to trim() will remove the leading and trailing whitespace, enabling the input to match “Illinois”.

Changing the case of characters within a string

It is sometimes helpful to change the case of the letters within a string. For example,  you might want to normalize the string for use by some other process. The method toLowerCase() converts all the characters in a string from upper to lowercase. The toUpperCase() method converts all the characters in a string from lowercase to uppercase. Nonalphabbetical characters, such as digits, are unaffected. Here are the simplest forms of these methods:

String toLowerCase()

String toUpperCase ()

Both methods return a String that contains the uppercase or lowercase equivalent of the invoking String.

public class ChnageCase {

    public static void main(String[] args) {

    String str = "This is a test";

    System.out.println("Original: "+str);

    String upper = str.toUpperCase();

    String lower = str.toLowerCase();

    System.out.println("Uppercase : "+upper);

    System.out.println("Lowercase : "+lower);

}   

}

 

The output of the above program is:

Original: This is a test

Uppercase: THIS IS A TEST

Lowercase: this is a test

Leave a Reply

Your email address will not be published. Required fields are marked *