Practical No: 4
Title: Program on String and String Buffer.
Theory:
String class
String class is used to create strings in java
It is present in java.lang package.
String class creates immutable string means once we create the string we cannot modify it either in content
or in length.
The variable declared as string reference can be changed to point at some other String object.
In java string can be created in two ways:
1. Using String Literal
String s1 = “Hello”;
2. Using new keyword
String s2 = new String(“Hello”);
StringBuffer class
StringBuffer class creates mutable strings that mean we can modify strings in terms of length and contents.
We can insert the character and substrings in the middle of the string, or we can append another string to
the end of string created using StringBuffer class.
String can be created using StringBuffer class using following constructors:
StringBuffer ( )
StringBuffer (String str)
Example:
StringBuffer str = new StringBuffer(“Hello”);
Difference between String and StringBuffer class
Programs:
1. Program to check if a string is a palindrome or not using in built functions.
import java.util.*;
public class PalindromeString
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter any String: ");
StringBuffer str = new StringBuffer(s.next());
String s1 = new String(str); //storing original string str in s1
String s2 = new String(str.reverse()); //reversing string str and storing it in s2
if(s1.equals(s2))
System.out.println("String is palindome");
else
System.out.println("String is not palindome");
}
}
2. Program to count the frequency of occurrence of a given character in a given line of text.
import java.util.*;
public class CharOccurrence
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter any line of text: ");
String str=s.nextLine();
System.out.println("Enter character to find its frequency of occurrence: ");
char ch=s.next().charAt(0);
int count=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==ch)
count++;
}
System.out.println("Count: "+count);
}
}
3. Program to demonstrate StringBuffer class and its methods
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Original string: "+sb);
sb.append(" World");
System.out.println("After appending: "+sb);
sb.insert(5," Java");
System.out.println("After inserting: "+sb);
sb.replace(6, 10, "RCPIT");
System.out.println("After replacing: "+sb);
sb.delete(6, 12);
System.out.println("After deleting: "+sb);
sb.reverse();
System.out.println("After reversing: "+sb);
}
}