Prepared by Manish ojha MCA
Unit VI String
6.1 Discuss the concept of string.
6.2 Construct string.
6.3 Describe string buffer and String builder class.
6.4 Elaborate string buffer method: append(), reverse(),
delete(),insert() methods.
6.5 Describe concept of string length.
6.6 Experiment the concatenate strings.
String: string can be defined as a set of characters enclosed within double
quotes. e.g “computer” , “1469” etc. Moreover, a set of digits enclosed
under double quotes is also treated as a string and not as number.
Assinging string variable Syntax:
<string data type> variable =<string literal>
e.g string st= “computer”;
String str= “1234”;
String buffer: string buffer type object has provision to change the
length. Change is maintained in the same object. It is advanced approach
of programming.
String buffer method:
1. Append( );
This is used to add a string at the end of another string.
Syntax: stringBuffer variable1.apppend(stringBuffer variable2);
e.g stringBuffer m=new stringBuffer(“Manish”);
stringBuffer n=new stringBuffer(“Bhanja”);
m.append(n);
It returns as ManishBhanja.
2. reverse( )
This is used to reverse the characters of a given string.
Syntax: stringBuffer variable.reverse();
e.g stringBuffer m=new stringBuffer(“Manish”);
m.reverse( );
It returns as reversed string hsinaM.
3. delete( ):
This function is applied to delete the characters from one index to another
index in a given string.
Syntax:stringBuffer variable.delete(index1,index2);
stringBuffer m=new stringBuffer(“computer”);
Unit VI programming in Java 1
Prepared by Manish ojha MCA
m.delete(3,5);
It will return as comer
4. insert( );
This function allows you to insert a string at specified index into the
another string.
Syntax: stringBuffer variable1.insert(stringBuffer variable2);
stringBuffer m=new stringBuffer(“computer fun”);
stringBuffer n=new stringBuffer(“is”);
m.insert(8,n);
It returns as computer is fun.
// A sample program to illustrate various String manipulation in
java.
public class Manipulation1 {
public static void main(String args[]) {
String a="manish";
String b="bhanja";
System.out.println("The length of the string manish="+a.length());
System.out.println("The concat of the strings="+a.concat(b));
}
// A sample program to illustrate various String manipulation2 in
java.
Note: compareTo:
Returns: negative if a<b
Positive if a>b
Zero if a=b
public class Manipulation2 {
public static void main(String args[])
{
StringBuffer m=new StringBuffer("Megh Nath Ojha");
String a="Manish";
String b="Ojha";
System.out.println("The reversed string ="+m.reverse());
System.out.println("The compare string="+a.compareTo(b));
Unit VI programming in Java 2
Prepared by Manish ojha MCA
}
Probable questions.
1. Define string.
2. List any four stringBuffer method.
3. Write a program to reverse the string “I am Manish”.
4. Write a program to concatenated two strings.
Unit VI programming in Java 3