10 String and String Buffer

10.1 THE STRING CLASS

The String class represents character strings. All string literals in Java programs, such as hello,1234 and xyz123 are implemented as instances of this class. Strings are constants and their values cannot be changed after they are created. String buffers support mutable strings, i.e., which can be modified. They will be discussed in the next section. Since String objects are immutable, they can be shared.

The declaration of String class from the Java documentation is given below.

public final class String extends Object implements Serializable,
Comparable<String>, CharSequence

This states that String is a final class and object is its super class. The class implements three interfaces.

As an elementary example of String class, consider the various ways of declaring and initializing String variables which are given below.

String str="hello";

is equivalent to

char data[]={'h','e','l','l','o'};
String str = new String(data);

or,

String str=new String("hello");

Some more examples of how strings can be used are given below.

System.out.println("hello");
String s="fun";
System.out.println("hello"+s);
String temp="hello".substring(2,3);
String var=temp.substring(1,2);

The + operator can be used for concatenation of strings. This is the only use of + operator in which Java supports operator overloading. For example:

String s="hello";
String str=s +"world";
System.out.println(str); //will print "hello world"
String str1="This " + " is "+" "demo";

is equivalent to

String str1 =" This is demo";

Similar to other primitive data types, a String variable must be initialized, i.e., the following program will give compilation error stating that 'variable str might not have initialized'

class JPS
{
   public static void main(String[] args)
   {
          String str;
          System.out.println(str);
   }
}

In order to rectify it, initialize the String variable str in the following way:

String str=null; or String str = new String();

Note: null is a special keyword which means that str does not contain reference of any String object. Printing a String object containing null will print null, but in the second case, using new operator it will print nothing.

10.2 CONSTRUCTORS FOR STRING CLASS

The String class provides a number of constructors that can be used in a variety of programming situations where strings are needed; some of the most common forms are discussed below.

1.   String()
This form of constructor initializes a newly created String object so that it represents an empty character sequence. It can be used in the following way:

String str=new String();
System.out.println(str); //prints blank

2.   String (byte[]bytes)
This form of constructor constructs a new String by decoding the specified array of bytes using the default charset of the platform. It can be used in the following way:

byte b[] = {'h','e','l','l','o'};
String s = new String(b);
System.out.println(s);

3.   String(byte[]bytes, int offset, int length)
This form of constructor constructs a new String by decoding the specified subarray of bytes using the platform's default charset. Staring from offset, length number of characters is taken from byte array b. It can be used in the following way:

byte b[]={'C','o','o','l','e','r'};
String s = new String(b,1,4);
System.out.println(s);            //prints oole

4.   String (char[]value)
This form of constructor allocates a new String so that it represents the sequence of characters currently contained in the character array argument. It can be used in the following way:

char ch[] = {'T','w','o','p','i','e'};
String s = new String(ch);
System.out.println(s);               //prints Twopie

5.   String(char[]value, int offset, int length)
This form of constructor allocates a new String so that it represents the sequence of characters currently contained in the character array argument. It can be used in the following way:

char ch[]={'T','w','o','p','i','e'};
String s = new String(ch,3,3);
System.out.println(s);               //prints pie

6.   String(String original)
This form of constructor initializes a newly created String object so that it represents the same sequence of characters as the argument. In other words, the newly created string is a copy of the argument String. It can be used in the following way:

String str="Cutie Pie";
String s = new String(str);
System.out.println(s);               // prints Cutie Pie
System.out.println(str);             // prints Cutie Pie

10.3 METHODS OF STRING CLASS

The class String includes methods for examining individual characters of the sequence, such as for comparing strings, for searching strings, for extracting substrings and for creating a copy of a string with all characters translated to uppercase or to lowercase. Some of the commonly used methods are explained with small code snippets in Java.

1.   The length() method

Signature: int length()

The length() gives the length of string in terms of number of characters. For example:

String str = "length";
int len =str.length();

will store 6 in variable len. It can be used in the following manner also.

len = "hello".length();        // len will have 5 as value

2.   The charAt method

Signature: char charAt(int index);

This method returns the character at the specified index. The first character is at index 0. For example:
char ch="fun".charAt(1);     //will store second character 'u' in ch
If the index is out of bound, i.e., not between 0 and string_length-1 then StringIndex OutOfBounds Exception will be thrown.

3.   The compareTo method

Signature: int compareTo(String s);

This method compares two strings lexicographically, i.e., according to dictionary and case of the letters on the basis of unicode character set. The uppercase letters have lower value than their corresponding lowercase counterparts. If the string being compared is greater than String s, a positive value is returned, negative value if String being compared is smaller than String s or 0 otherwise. The case of characters is also considered while comparing the two strings. The characters have been their ASCII value while comparing strings. For example:

String str1 = "Java", str2 ="java";
int c =str1.compareTo(str2);
if(c>0)
System.out.println(str1+" is greater");
else if(c<0)
System.out.println(str2+" is greater");
else
System.out.println("Both are equal");

As 'j' is greater than 'J', first if condition is true and 'java is greater' will be printed.

4.   The compareToIgnoreCase method

Signature: int compareToIgnoreCase(String s);

This method is similar to compareTo method with the difference that uppercase and lowercase letters are considered the same. Following the above example, 'java', 'Java' and 'JAVA' should all be treated the same.

5.   The concat method

Signature: String concat (String s);

This method concatenates the specified string s to the end of this string. If the length of the argument string is 0 the String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. For example:

"devote".concat("es")returns "devotes"
"to".concat("get").concat("her")returns"together"

6.   The equals method
Signature: boolean equals(Object obj)
This method compares this string to the specified object. The result is true only if the argument is not null and is a String object that represents the same sequence of characters as this object. It is similar to compareTo method and the only difference is that it returns only true or false value of type Boolean. For example:

"fun".equals("fun")returns true;
"boom".equals("Boom")returns false;

7.   The equalsIgnoreCase method
Signature: boolean equals(Object obj)
This method compares string to the object without considering the case. For example:

"fun".equals("Fun")returns true;
"boom".equals("Boomer")returns false;

8.   The endsWith method
Signature: boolean endsWith (String suffix)
This method tests if this string ends with the specified suffix.

String str="Education";
String str1="Explanation";
boolean b1=str.endsWith("tion");
boolean b2=str1.endsWith("nation");

b1 and b2 gets true as their value.

9.   The getChars method
Signature: void getChars(int srcBegin, int srcEnd, char[]dst, int dstBegin)
This method copies characters from this string into the destination character array. The first character to be copied is at index srcBegin and the last character at index srcEnd-1 (thus, the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the sub-array of dst starting at index dstBegin and ending at index:

dstbegin + (srcEnd-srcBegin)-1

For example:

String str="Education";
char[]arr=new char[str.length()];
str.getChars(3,str.length(),arr,0);
System.out.println(arr);    //displays "cation"

10. The indexOf method
Signature: int indexOf(int ch)
This method returns the index within this string of the first occurrence of the specified character. If the character is not within the string-1 is returned. For example:

int x = "Index".indexOf('d'), //return 2

images

Figure 10.1 Diagrammatical implementation of indexOf method

The second overloaded form of indexOf method is as follows:

int indexOf(int ch, int fromindex);

where fromindex is the starting index from which search is to start. For example:

int x = "Explanation".indexOf('n',6);

images

Figure 10.2 Implementation of overloaded indexOf method

Returns 10 as starting from 6th index (7th character) 'n' is at 10th position as shown in Figure 10.2.

11. The lastIndexOf method
Signature: int lastIndexOf(int ch);
This method returns the index within this string of the last occurrence of the specified character -1 if the character does not occur in the string. For example:

"abcdacd".lastIndexOf('a'), //returns 4

12. The replace method
Signature: String replace (char oldChar, char newChar)
This method returns a new string from replacing all occurrences of oldChar in this string with newChar.

String s ="Krish".replace('i','r'), //store "Krrsh" in s.

images

Figure 10.3 Implementation of replace method

The other form of replace is to replace a substring with a new string. For example:

String str = " This is new string";
String s = str.replace("new","old");
System.out.println(s);

The string s will have 'This is old string'.

13. The startsWith method
Signature: boolean startsWith(String prefix);
This method tests if this string starts with the specified prefix. For example:

 "presume".startsWith("pre"); //returns true;

14. The substring method
Signature: String substring(int beginIndex)
This method returns a new string that is a substring of this string. For example:

String str = "This is new string";
String s = str.substring(5);
System.out.println(s);            //s will print "is new string"

The other overloaded form is as follows:

String substring(int beginIndex, int endIndex)

This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex-1. Thus the length of the substring is endIndex-beginIndex. For example:

String str="This is new string";
String s = str.substring(8,11);
System.out.println(s);            //s will print "new"

15. The tocharArray() method
Signature: char[]toCharArray()
This method converts this string to a new character array. It returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. For example:

String str = "Gorgeous";
char[]arr=str.toCharArray();
System.out.println(arr);     //arr prints "Gorgeous"

16. The toLowerCase method
Signature: String toLowerCase()
This method converts all of the characters in this String to lower case. For example:

String str = "HEALTHY";
System.out.println(str.toLowerCase());//will print"healthy"

17. The toUpperCase method
Signature: String toUpperCase()
This method converts all of the characters in this String to uppercase. For example:

String str = "healTHY";
System.out.println(str.toUpperCase()); //willprint"HEALTHY"

18. The toString method
Signature: String toString()
This object (which is already a string) is itself returned. This method is used internally when something is printed which is not a string using println method. The data types or objects are first converted to String objects using the toString method and then displayed. One such usage has been observed in displaying the objects of class.

19. The trim method
Signature: String trim()
The method returns a copy of the string with leading and trailing white space omitted. For example:

String str = " 	Free	 ";
System.out.println(str.trim());

20. The getBytes method
Signature: byte[] getBytes()
This method encodes this String into a sequence of bytes using the platform's default charset, sorting the result into a new bytes array. For example:

String str = "Cutie Pie";
byte b[]=str.getBytes();
for(int i=0;i<b.length;i++)
System.out.println((char)b[i]);     //prints Cutie Pie

Without typecasting by char output will be Unicode codes of the characters.

21. The valueOf method
There are five overloaded valueOf methods which convert primitive values into String objects. All methods are static and return a String object. The signature is as follows:

public static String valueOf(type b);

The type may be int, double, char, float and boolean. For example:

String dvalue = String.valueOf(123.456);
String fvalue = String.valueOf(654.854f);
String ivalue = String.valueOf(123);
String bvalue = String.valueOf(true);
String cvalue = String.valueOf('p'),

System.out.println(dvalue);        //prints 123.456
System.out.println(fvalue);        //prints 654.854
System.out.println(ivalue);        //prints 123
System.out.println(bvalue);        //prints true
System.out.println(cvalue);        //prints p

10.4 PROGRAMMING EXAMPLES (PART 1)

/*PROG 10.1 REVERSING A STRING*/
import MYIO.*;
class JPS1
{
   public static void main(String args[])
   {
          String str=null;
          MYINOUT.show("
Enter the string:=");
          str=MYINOUT.str_val();
          char[]arr=new char[str.length()];
          for(int i=str.length()-1,j=0;i>=0;i--,j++)
                arr[j]=str.charAt(i);
          String revstr = new String(arr);
          MYINOUT.show("
Reverse string is:=
                       "+revstr+"
");
   }
}

OUTPUT:

Enter the string:=NMIMS UNIVERSITY
Reverse string is:= YTISREVINU SMIMN

Explanation: As the own methods for handling the input and output package are being used, MYIO is imported in the program created in the chapter entitled Packages and Interfaces. The logic to reverse the string is simple. First, a new char array is created using the length() method of string as the size of the array. Now, using for loop and charAt method of string one character is extracted at a time from the string from last and put in the beginning of the array. For that variables i and j have been used. In each iteration of for loop i is decremented and j is incremented. In the end, the array arr is converted to a String and stored in revstr which contains reverse string. This revstr is then displayed.

/*PROG 10.2 CHECKING STRING FOR PALINDROME*/
import MYIO.*;
class JPS2
{
   public static void main(String args[])
   {
          String str = null;
          MYINOUT.show("
 Enter the string:=");
          str = MYINOUT.str_val();
          char[] arr = new char[str.length()];
          for (int i = str.length()-1,j=0;i>=0;i--,j++)
                 arr[j] = str.charAt(i);
          String revstr = new String(arr);
          MYINOUT.show("
 Reverse string is:= "+revstr+"
");
          boolean flag = str.equals(revstr);
          if (flag == true)
                 MYINOUT.show("
 String is palindrome
");
          else
                 MYINOUT.show("
 String is not
palindrome
");
   }
}

OUTPUT:

(First Run)
Enter the string:=PEEP
Reverse string is:= PEEP
String is palindrome

(Second Run)

Enter the string:=MPSTME
Reverse string is:= EMTSPM
String is not palindrome

Explanation: After reversing the string, the two strings are compared using equals method. If equals returns true it means the string is palindrome else the string is not palindrome.

/* PROG 10.3 ARRAY OF STRINGS */
import MYIO.*;
class JPS3
{
   public static void main(String args[])
   {
          String[] str ={ null };
          int size;
          MYINOUT.showln("
Enter how many strings");
          size = MYINOUT.int_val();
          str = new String[size];
          int i;
          for (i = 0; i < size; i++)
          {
             MYINOUT.showln("
Enter string number "+(i+1));
                str[i] = new String();
                str[i] = MYINOUT.str_val();
          }
          MYINOUT.showln("
Strings entered are");
          for (i = 0; i < size; i++)
                MYINOUT.showln(str[i]);
   }
}

OUTPUT:

Enter how many strings
3

Enter string number 1
NMIMS UNIVERSITY

Enter string number 2
PHI PUBLICATION

Enter string number 3
HARI MOHAN PANDEY

Strings entered are
NMIMS UNIVERSITY

PHI PUBLICATION
HARI MOHAN PANDEY

Explanation: String is a class in Java and creating an array of String means creating an array of object. Initially, all the String elements are initialized to null . Each String object has to be initialized before it can be put to use. In the for loop before taking String from the user, the line str[i] = new String(); does the same. The next value for all the strings is taken and using one more for loop they are displayed.

/* PROG 10.4 SORTING OF STRINGS */
import MYIO.*;
class JPS4
{
   public static void main(String args[])
   {
          String[] str = { null };
          String temp = null;
          int size;
          MYINOUT.showln("Enter how many strings");
          size = MYINOUT.int_val();
          str = new String[size];
          int i, j;
          for (i = 0; i < size; i++)
          {
          MYINOUT.showln("Enter string number "+(i+1));
                 str[i] = new String();
                 str[i] = MYINOUT.str_val();
          }
          MYINOUT.showln("Sorted strings are");
          for (i = 0; i < size; i++)
            for (j = i + 1; j < size; j++)
             if (str[i].compareTo(str[j]) > 0)
             {
                 temp= str[i];
                 str[i] = str[j];
                 str[j] = temp;
             }
          for (i = 0; i < size; i++)
          MYINOUT.showln(str[i]);
   }
}

OUTPUT:

Enter how many strings
4
Enter string number 1
Hari
Enter string number 2
Ravi
Enter string number 3
Vijaya
Enter string number 4
Ranjana
Sorted strings are
Hari
Ranjana
Ravi
Vijaya

Explanation: For sorting the strings, the same logic is followed as was done for sorting the array of integers, float, etc. Two for loops are used and using compareTo method, the first two strings are compared, and if first string is greater than the second one (lexicographically) they are swapped. This continues and in the end the sorted strings result.

/*PROG 10.5 DEMO OF TOSTRING METHOD */
import java.io.*;
class Fruit
{
   String name;
   String color;
   boolean contain_seed;
   Fruit(String n, String c, boolean cs)
   {
          name = n;
          color = c;
          contain_seed = cs;
   }
          public String toString()
          {
                String str = "Fruit Name = " + name;
                str = str + "
Fruit Color = " + color;
                str = str + "
Fruit contains seed = " +
                              contain_seed + "
";
                return str;
          }
   }
   class JPS5
   {
          public static void main(String[] args)
   {
          Fruit F1 = new Fruit("Banana", "Yellow", false);
          Fruit F2 = new Fruit("Apple", "Red", true);
          System.out.println("	Fruit 1");
          System.out.println(F1);
          System.out.println("	Fruit 2");
          System.out.println(F2);
   }
}

OUTPUT:

   Fruit 1
Fruit Name = Banana
Fruit Color = Yellow
Fruit contains seed = false
   Fruit 2
Fruit Name = Apple
Fruit Color = Red
Fruit contains seed = true

Explanation: The main lines shown in bold have arguments as object of class Fruit. Objects cannot be displayed in this manner. But the method toString helps one in these types of situations. In order to display objects in the above manner, all one needs to do is to define toString method as shown in the program. The method is called automatically to convert the object F1 and F2 into Strings. In the method toString the strings are concatenated which are to be displayed and in the end the string is returned. If toString is not overridden the compiler will flash error. This method can be used to print any object of an user-defined class.

10.5 THE STRINGBUFFER CLASS

A stringBuffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The declaration of the StringBuffer class as given in the Java documentation is as follows:

public final class StringBuffer extends Object
implements Serializable, CharSequence

This states that StringBuffer is a final class extending the Object class. The class implements two interfaces.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer and the insert method adds the characters at a specified point.

For example, if sbuf refers to a string buffer object whose contents are 'jul', then the method class sbuf.append('le') would cause the string buffer to contain 'julle', whereas sbuf.insert(1, 'le') would alter the string buffer to contain 'jleul'.

In general, if sb refers to an instance of a StringBuffer, sb.append(x) has the same effect as sb.insert(sb.length(), x).

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

10.6 CONSTRUCTOR OF STRINGBUFFER CLASS

The StringBuffer class defines three main constructors for using StringBuffer objects in the programs.

1.   StringBuffer()
This form of constructor constructs a string buffer with no characters in it and an initial capacity of 16 characters. It can be used as follows:

StringBuffer sb = new StringBuffer();

2.   StringBuffer(int capacity)
This form of constructor constructs a string buffer with no characters in it and the specified initial capacity. The initial capacity becomes the size of the buffer. The above form can be used as follows:

StringBuffer sb = new StringBuffer(5);

3.   StringBuffer(String str)
This form of constructor constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument. It can be used as follows:

StringBuffer sb = new StringBuffer("demo");

Here, the capacity of object sb is 4 + 16, i.e., 20. Java keeps room for additional 16 characters to avoid reallocation problems. By providing extra capacity for 16 characters, the number of reallocation is reduced as it is time-consuming.

10.7 METHODS OF STRINGBUFFER CLASS

There are a number of methods which are common to String and StringBuffer class. Only those methods are discussed which are unique to StringBuffer class. However, listing of frequently used methods is given in Table 10.1.

S. No. Name of Method
1 append
2 capacity
3 charAt
4 delete
5 deleteCharAt
6 ensureCapacity
7 getChars
8 indexOf
9 insert
10 lastIndexOf
11 length
12 replace
13 reverse
14 setCharAt
15 setlength
16 substring
17 toString
18 trimToSize

Table 10.1 Methods of StringBuffer class

1.   The capacity method
Signature: int capacity()
This method returns the current capacity of the StringBuffer object. The initial capacity is of 16 characters when no characters are present in the buffer. As characters are entered into the buffer, the capacity is usually added to the length of StringBuffer object.
Example:

StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); //prints 16

2.   The delete method
Signature: StringBuffer delete (int start, int end)
This method removes the characters in a substring of this sequence. This substring begins at the specified start and extends to the character at index end-1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.
Example:

StringBuffer sb = new StringBuffer("Demolition");
sb.delete(4,6);// deletes characters at position 4 and 5.
System.out.println(sb); //prints "Demotion".

3.   The deleteCharAt method
Signature: StringBuffer deleteCharAt(int index)
This method removes the char at the specified position in this sequence.
Example:

StringBuffer sb = new StringBuffer("Funn");
sb.deleteCharAt(2);
System.out.println(sb);     //prints "Fun"

4.   The reverse method
Signature: StringBuffer reverse()
This method causes this character sequence to be replaced by the reverse of the sequence.
Example:

StringBuffer sb = new StringBuffer("Fantastic");
System.out.println(sb.reverse()); //prints citsatnaF

5.   The setChatAt method
Signature: void setCharAt(int index, char ch);
The character at the specified index is set to ch.
Example:

sb.setCharAt(2,'s'),
sb.setCharAt(3,'s'),
System.out.println(sb); //prints "Fuss"

6.   The ensureCapacity method
Signature: void ensureCapacity(int capacity);
This method ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, a new internal array is allocated with greater capacity. The method can be used where it is known in advance that a large number of strings will be appended to the StringBuffer object.

Example:

StringBuffer sb = new StrignBuffer(5);
System.out.println(sb.capacity());
sb.ensureCapacity(20);
System.out.println(sb.capacity());

7.   The setLength method
Signature: void setLength(int newLength);
This method sets the length of the StringBuffer object. The sequence is changed to a new character sequence whose length is specified by the argument. If the newLength argument is greater than or equal to the current length, sufficient null characters are appended so that length becomes the newLength argument. In case, newLength is less than the current length characters are lost from the character sequence.

StringBuffer sb = new StringBufer("Demo of String   Buffer");
System.out.println("Before setting length");
System.out.println("sb="+sb+", Length = "+sb.length());
sb.setLength(15);
System.out.println("After setting length");
System.out.println("sb="+sb+",Length="+sb.length());

Output of the above code is as follows:

Before setting length
sb= Demo of String Buffer, Length = 21
After setting length
sb = Demo of String, Length = 15

8.   The append method
The append method is used for appending any primitive type of data at the end of invoking StringBuffer object. Any primitive data type means that the method is overloaded for different types of elementary data types and also for the Object class. Its general form is as follows:
Signature: StringBuffer append (type t);
where t may be char, int, long, double, float, Object, etc. The method returns a StringBuffer object after the append operation is over. This makes it possible to chain together more than one append methods.
Example 1:

StringBuffer sb = new StringBuffer("Rosy");
sb.append("Lips");
sb.append(true);
sb.append(123);
System.out.println(sb);           //print Rosy Lipstrue123

Example 2:

StringBuffer sb = new StringBuffer("Chubby");
sb.append("Cheeks").append("Rosy").append("Lips");
System.out.println(sb);
output is : Chubby Checks Rosy Lips

9.   The insert method
The insert method has a number of overloaded forms. Some of them are discussed below.

public StringBuffer insert(int ioffset, type d);

The method inserts d into this StringBuffer instance at offset ioffset. The type may be int, char, double, boolean, float, long, char[], Object and String.
Example:

StrignBuffer sb = new StringBuffer(20);
sb.insert(0,"Hello");
sb.insert(2,true);
sb.insert(3,23.45);
System.out.println(sb);

The output of the code is Het23.45ruello

10.8 PROGRAMMING EXAMPLES (PART 2)

/*PROG 10.6 STRINGBUFFER DEMO VER 1*/
import MYIO.*;
class JPS6
{
   public static void main(String args[])
   {
          StringBuffer sb = new StringBuffer("Buffer");
          MYINOUT.showln("Capacity = " + sb.capacity());
          MYINOUT.showln("Buffer contents =" + sb);
          MYINOUT.showln("Buffer Length = " + sb.length());
   }
}

OUTPUT:

Capacity = 22
Buffer contents = Buffer
Buffer Length = 6

Explanation: The capacity shown as output is the sum of the initial capacity, i.e., 16 characters plus length of the contents 'Buffer' The rest is simple to understand.

/*PROG 10.7 STRINGBUFFER DEMO VER 2 */
import MYIO.*;
class JPS7
{
   public static void main(String args[])
   {
          StringBuffer sb = new StringBuffer("Buffer");
          MYINOUT.showln("Capacity = " + sb.capacity());
          MYINOUT.showln("Buffer contents = " + sb);
          MYINOUT.showln("Buffer Length = " + sb.length());
          sb.append("Temporary");
          sb.insert(6, " is ");
          sb.append(" storage");
          MYINOUT.showln("Capacity = " + sb.capacity());
          MYINOUT.showln("Buffer contents = " + sb);
          MYINOUT.showln("Buffer Length = " + sb.length());
   }
}

OUTPUT:

Capacity = 22
Buffer contents = Buffer
Buffer Length = 6
Capacity = 46
Buffer contents = Buffer is Temporary storage
Buffer Length = 27

Explanation: The program is simple to understand.

10.9 PONDERABLE POINTS

1.   A String is a class in Java defined in the package java.lang.

2.   All variables of String class are its object which must be initialized before they can be used.

3.   All string variables are of fixed length which can be found out by using length method.

4.   A string object can provide flexible strings whose length can increase and decrease.

5.   The StringBuffer class provides flexible strings whose length can increase and decrease.

6.   The default capacity of a StringBuffer object is 16 characters.

REVIEW QUESTIONS

1.   Distinguish between the following terms:

(a) String and StringBuffer

(b) Length and length()

(c) equal and ==

(d) length() and capacity()

(e) setCharAt() and insert()

2.   What is wrong in the following code:

Vector v = new Vector(10);
v.addElement(21);

3.   Write a program that accepts a name list of five students from the command line and store in a vector.

4.   Write a program to generate Fibonacci series where the data are saved in vector.

5.   Write a method called remove (String s1, int n) that returns the input string with nth element removed.

6.   What will be the output of the following program?

class JPS_test
{
   static String b;
   public static void main(String args[])
   {
                String a = new String();  //empty string
                System.out.println("a = " + a);
                System.out.println("b = " + b);
   }
}

7.   What will be the output of the following program?

class JPS_test
{
    public static void main(String args[])
    {
                 String S1 = new String("Hari"); //empty string
                 String S2;
                 S2 = S1;
                 if (S1 == S2)
                 System.out.println("Hari O Hari");
                 System.out.println("Sorry, I'm unhappy");
   }
}

8.   Write and run the following Java program that does the following:

(a) Declare a string object named s1 containing the string "Object Oriented Programming-Java 5".

(b) Print the entire string.

(c) Use the length() method to find the length of the string.

(d) Use the charAt() method to find the first character in the string.

(e) Use charAt() and length() methods to print the last character in the string.

(f) Use the indexOf() and the substring() method to print the first word in the String.

9.   Try to compile a program containing the lines

String s;
String s;

Does Java allow this? If not, what message do you get?

10. What message does the compiler give if we try to compile a program containing the statements:

s = "hello";
String s;

11. Try to compile a program containing the lines

String s;
PrintStream s;

Does Java allow this? If not, what message do you get?

12. Suppose that a class defines a method with the prototype

String first(String)

Give two other methods that can be defined in the class.
Give two other methods that cannot be defined in the class.

13. Show the order of evaluation for the expression:

"h e l l o" . t o U p p e r C a s e().
concat("there");

14. What error message does Java give if a program contains the following line?

System.out.println("hello".toUp-
perCase);

Multiple Choice Questions

1.   String as a class in Java is defined in

(a) java.io package

(b) java.awt package

(c) java.lang package

(d) java.applet package

2.   The default capacity of a StringBuffer object is

(a) 8 characters

(b) 16 characters

(c) 32 characters

(d) 64 characters

3.   The method returns the character at the specified index

(a) char charAt(int index);

(b) char charAt[int index];

(c) int charAt(int index);

(d) int charAt[int index];

4.   The method used for testing the if string ends with the specified suffix

(a) int endswith(String suffix)

(b) char endsWith(String suffix)

(c) boolean endsWith(String suffix)

(d) None of the above

5.   The getChars method is used to copy characters from this string into the destination character array. The signature of the method getChars is:

(a) void getChars(int srcBegin, int srcEnd, char[]dst, int dstBegin)

(b) int getChars(int srcBegin, int srcEnd, char[]dst, int dstBegin)

(c) boolean getChars (int srcBegin, int srcEnd, char[]dst, int dst Begin)

(d) None of the above

6.   The indexOf method is used to return the index within this string of the first occurrence of the specified character. If character is not within the string, it returns

(a) 0

(b) +1

(c) -1

(d) 2

7.   In Java______________method is used for testing if this string starting with the specified prefix

(a) int startsWith(Stringprefix)

(b) void startswith(String prefix)

(c) boolean startsWith(String prefix)

(d) long startsWith(String prefix)

8.   If the method returns a copy of the string, with the leading and trailing white space omitted it is a

(a) toString method

(b) getBytes method

(c) trim method

(d) tocharArray method

9.   StringBuffer sb = new StringBuffer(10);

In the code snippet shown above 10 shows:

(a) index number for the string

(b) capacity

(c) reference number

(d) none of the above

10. The StringBuffer class provides flexible strings whose length can

(a) increase only

(b) decrease only

(c) increase and decrease as per the need

(d) neither increase nor decrease—fixed at the initial stage

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   c

2.   b

3.   a

4.   c

5.   a

6.   c

7.   c

8.   c

9.   b

10. c

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.63.95