6 String and String Buffer







String Class
A String is a series of characters and is different from any array of characters.  It is an object which implies once a string is created, we can not change it.  This makes the strings to be constant.  Objects of string class can not grow once they are created.  The ‘+’ operator is used to join two strings together.

String Literals
String literals are created, by specifying characters in double quotes.  They are called literals because their value is constant and can not change.  For example:
String name = “P. Pandit”;

String Pool
Whenever a string is created, internally it is treated as an instance of a String.  A Java program can contain many string literals.  Hence it holds  a String Pool that represents all the literals created in the program.  Whenever a string literal is created, the String Pool is searched to see if it exists.  If the string literal is exists, new instance is not created for that String Pool.  Here an existing instance is assigned to the new string.  This saves lot of memory space.  For example:

String day = “Monday”;
String weekday = “Monday”;

Here an instance for the day whose value is Monday is created in the String Pool.  When the variable named weekday is created holding same value as the variable day, an existing instance is assigned to the variable weekday.  So both day and weekday point to the same string in the String Pool.

Example 1( String Concat)
class StringCon
{
public static void main(String ars[])
{
String A = new String("Sandhyashree");
String B = new String("Sports");
String C = new String("Leena's ");
String D = new String("Software");
System.out.println(" ");
System.out.println("String Before Concatenation without + Operator");
System.out.println(A);
System.out.println(B);
System.out.println(" ");
A = A+ " " +B;
System.out.println("String After Concatenation with + Operator");
System.out.println(A);
System.out.println(" ");

System.out.println("String Before Concatenation without Concat Function");
System.out.println(C);
System.out.println(D);
System.out.println(" ");
System.out.println("String After Concatenation with Concat Function");
C=C.concat(D);
System.out.println(" ");
System.out.println(C);
}
}

Example 2(String Constructor)
class StringCons {
public static void main(String ars[]) {
String str1 = new String( );
String str2 = new String("Hello Guies");
char ch[] = {'A','B','C','D','E'};
String str3 = new String(ch);
String str4 = new String(ch,0,2);
System.out.println(str1);
System.out.println(" ");
System.out.println(str2);
System.out.println(" ");
System.out.println(str3);
System.out.println(" ");
System.out.println(str4);
}
}

String class methods
String class provides different methods.  The methods are divided as follows:

Return_type Method name (parameters) Set 1
Ø  char charAt(int index)
Ø  boolean endsWith(String suffix)
Ø  boolean startsWith(String suffix)
Ø  int length( )

Example 3(String Method 1 )
class StringMethod{
public static void main(String ars[]){
String name = new String("Anand Infotec");
char ch = name.charAt(5);
System.out.println("character at 5 th Index is "+ch);
int length=name.length( );
System.out.println(" ");
System.out.println("Length of name is  "+length);
if(name.startsWith("Anand")) {
System.out.println("Name starts with Anand");
}
if(name.endsWith("Infotec")){
System.out.println("Name ends with Infotec ");
}
}
}

Return_type Method name (parameters) Set 2
Ø  String copyValueOf(char ch[ ], int start_index, int count)
Ø  String copyValueOf(char ch [ ] )
Ø  char [ ] toCharArray( )

Return_type Method name (parameters) Set 3
Ø  int indexOf(char ch)
Ø  int indexOf(char ch, int startindex)
Ø  int indexOf(String str)
Ø  int indexOf(String str, int startindex)

Return_type Method name (parameters) Set 4
Ø  int lastindexOf(char ch)
Ø  int lastindexOf(char ch, int startindex)
Ø  int lastindexOf(String str)
Ø  int lastindexOf(String str, int startindex)

Return_type Method name (parameters) Set 5
Ø  boolean equals(Object ob)
Ø  String toUpperCase(String)
Ø  String toLowerCase(String)
Ø  String trim( )

Return_type Method name (parameters) Set 6
Ø  String substring(int index)
Ø  String substring(int startindex, int endindex)
Ø  String valueOf(double)
Ø  String valueOf(Boolean)
Ø  String valueOf(char)

StringBuffer class
The String class is used to support operations on strings of characters.  The String class supports constant strings.  Often it so happens that, strings have to be modified.  That is insertions/deletions might be necessary in some part of the strings.  This can not be done or handled by the String class, but by the StringBuffer class.  StringBuffer class provides various methods to manipulate string object.  StringBuffer class supports growable, modifiable strings.

Thus objects of StringBuffer class are expandable and flexible.  Characters of strings can be inserted in between in the StringBuffer object as well as they can be appended at the end.  The various StringBuffer methods are as follows:-

Set 1
Ø  StringBuffer append(String str)
Ø  StringBuffer append(char ch [ ] )
Ø  StringBuffer append(char ch [  ], int offset, int length)
Ø  StringBuffer append(int no)

Example 4(String Buffer Constructor)
class StringBuffCons{
public static void main(String ars[]){
StringBuffer s1 = new StringBuffer( );
StringBuffer s2 = new StringBuffer(20);
StringBuffer s3 = new StringBuffer("String Buffers");
StringBuffer s4 = new StringBuffer(5);
System.out.println("s3 = " +s3);
System.out.println("length of s2  "+s2.length( ));
System.out.println("length of s3  "+s3.length( ));
System.out.println("capacity of s1  "+s1.capacity( ));
System.out.println("capacity of s2  "+s2.capacity( ));
System.out.println("capacity of s3  "+s3.capacity( ));
System.out.println("capacity of buffer s4 "+s4.capacity( ));
s4.ensureCapacity(8);
System.out.println("capacity of buffer s4 "+s4.capacity( ));
s4.ensureCapacity(30);
System.out.println("capacity of buffer s4 "+s4.capacity( ));
}
}

Set 2
Ø  StringBuffer insert(int insertposition, String str)
Ø  StringBuffer insert(int insertposition, char ch)
Ø  StringBuffer insert(int insertposition, float f)

Set 3
Ø  char charAt(int index)
Ø  void setCharAt(int index, char ch)
Ø  void getChars(int begin, int end, char destination[ ], int begin)
Ø  void setLength(int length)
Set 4
Ø  StringBuffer reverse( )


Practical Examples

Example 1(String Methods1)
class StringMethods1
{
public static void main(String ars[]){
char name[] = {'A','n','a','n','d','I','n','f','o','t','e','c'};
String subname=String.copyValueOf(name,5,3);
System.out.println(subname);
String fullname=String.copyValueOf(name);
System.out.println(fullname);
String text = new String("Hello World");
char textArray[]=text.toCharArray( );
for(int i=6;i<text.length( );i++)
System.out.print(textArray[i]+"\t");
}
}
Example 2(String Methodss2)
class StringMethods2 {
public static void main(String args[]) {
String day = new String("Sunday");
int index1 = day.indexOf('n');
System.out.println("Index of Character 'n' " +index1);
int index2 = day.indexOf('n',3);
if(index2==-1)
System.out.println("Index of Character 'n' not found");
int index3 = day.indexOf("Sun");
System.out.println("Index of String Sun is "+index3);
int index4 = day.indexOf("day");
System.out.println("Index of String day from specified index is "+index4);
String day1 = new String("Sunday Monday");
int index5 = day1.lastIndexOf('n');
System.out.println("Last Index of Character 'n' " +index5);
int index6 = day1.lastIndexOf('n',7);
if(index6==-1)
System.out.println("Last Index of Character 'n' not found");
else
System.out.println("Last Index of Character 'n' " +index6);
int index7 = day1.lastIndexOf("ay");
System.out.println("Last Index of String ay is "+index7);
int index8 = day1.lastIndexOf("day",6);
System.out.println("Index of Character day from specified index is " +index8);
}
}
Example 3(String Methodss3)
class StringMethod3{
public static void main(String args[]){
String lower = new String("good morning");
System.out.println(lower +"in Upper Case : "+lower.toUpperCase( ));
String upper = new String("Sandhyashree");
System.out.println(upper +"in Lower Case : "+upper.toLowerCase( ));

String spaces = new String("    Spaces ");
System.out.println(spaces +"after Trimming : "+spaces.trim( ));
String text1 = new String("TEXT");
String text2 = new String("TEXT");
if (text1.equals(text2))
System.out.println("Text 1 and Text2 are Equal ");
System.out.println(" ");
String text3 = new String("An Apple a Day keeps Doctor Away");
String sub1 = text3.substring(text3.indexOf('k'));
System.out.println(sub1);
String sub2 = text3.substring(3,8);
System.out.println(sub2);
System.out.println(String.valueOf(45.00));
System.out.println(String.valueOf(true));
System.out.println(String.valueOf('$'));
String replacedStr = text3.replace(' ','*');
System.out.println(replacedStr);
}
}

Example 4(String Buffer Method1)
import java.awt.*;
class StringBuffMethod1{
public static void main(String args[]){
StringBuffer s1= new StringBuffer("Microsoft");
System.out.println("s1 before append " +s1);
System.out.println("s1 after append " );
s1.append("Windows XP");
System.out.println("s1 "+s1 );
char ch[]={' ','C','l','a','s','s'};
char ch1[]={'O','n','e','E','x','a','m','p','l','e'};
s1.append(ch);
System.out.println("s1 "+s1 );
s1.append(ch,0,1);
s1.append(ch1,3,7);
System.out.println("s1 "+s1 );
s1.append(1);
System.out.println("s1 "+s1 );
}
}

Example 5(String Buffer Method2)
import java.awt.*;
class StringBuffMethod2{
public static void main(String args[]){
StringBuffer s1= new StringBuffer("Java sion");
System.out.println("s1 before append " +s1);
System.out.println("s1 after append " );
s1.insert(5,"Ver");
System.out.println("s1 "+s1 );

s1.append(" For You");
System.out.println("s1 "+s1 );
s1.insert(13,1.2);
System.out.println("s1 "+s1 );
s1.insert(16,' ');
System.out.println("s1 "+s1 );
}
}

Example 6(String Buffer Method3)
import java.awt.*;
class StringBuffMethod3{
public static void main(String args[]){
String name="James Gosling - Inventor of Java";
StringBuffer s1= new StringBuffer (name);
if(s1.charAt(14)=='-')
s1.setCharAt(14,':');
System.out.println("s1 "+s1 );
char ch[] = new char[14];
s1.getChars(0,13,ch,0);
System.out.println("New array is " +String.valueOf(ch));
s1.setLength(s1.length( )+10);
System.out.println("s1 "+s1 );
s1.setLength(5);
System.out.println("s1 "+s1 );
}
}

Example 7(String Buffer Reverse Method)
import java.awt.*;
class reverseString{
public static void main(String args[]){
System.out.println("Original String   Reversed String");
for(int i =0;i<args.length;i++){
StringBuffer str = new StringBuffer(args[i]);
System.out.println("  "+args[i]+"\t\t\t"+ "  "+str.reverse( ));
}
}
}

No comments:

Post a Comment