OOPM JAVA - demonstrate all String and StringBuffer class methods

Experiment No. 08

Aim : Write a program to demonstrate  all String and StringBuffer class methods Write a program to reverse a string and check it is palindrome or not.

Objective: To make aware of specialized character string classes String and StringBuffer their use 

Outcome: Students implemented different methods from String and StringBuffer class and their usage.

Theory: 

Java String

In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:

         char[] ch={'j','a','v','a','t','p','o','i','n','t'};

         String s=new String(ch);

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

What is String in java

Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.

 

How to create String object?

There are two ways to create String object:

By string literal

By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String s1="Welcome"; 

String s2="Welcome";//will not create new instance

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

  

No.

Method

Description

1

char charAt(int index)

returns char value for the particular index

2

int length()

returns string length

3

static String format(String format, Object... args)

returns formatted string

4

static String format(Locale l, String format, Object... args)

returns formatted string with given locale

5

String substring(int beginIndex)

returns substring for given begin index

6

String substring(int beginIndex, int endIndex)

returns substring for given begin index and end index

7

boolean contains(CharSequence s)

returns true or false after matching the sequence of char value

8

static String join(CharSequence delimiter, CharSequence... elements)

returns a joined string

9

static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

returns a joined string

10

boolean equals(Object another)

checks the equality of string with object

11

boolean isEmpty()

checks if string is empty

12

String concat(String str)

concatinates specified string

13

String replace(char old, char new)

replaces all occurrences of specified char value

14

String replace(CharSequence old, CharSequence new)

replaces all occurrences of specified CharSequence

15

static String equalsIgnoreCase(String another)

compares another string. It doesn't check case.

16

String[] split(String regex)

returns splitted string matching regex

17

String[] split(String regex, int limit)

returns splitted string matching regex and limit

18

String intern()

returns interned string

19

int indexOf(int ch)

returns specified char value index

20

int indexOf(int ch, int fromIndex)

returns specified char value index starting with given index

21

int indexOf(String substring)

returns specified substring index

22

int indexOf(String substring, int fromIndex)

returns specified substring index starting with given index

23

String toLowerCase()

returns string in lowercase.

24

String toLowerCase(Locale l)

returns string in lowercase using specified locale.

25

String toUpperCase()

returns string in uppercase.

26

String toUpperCase(Locale l)

returns string in uppercase using specified locale.

27

String trim()

removes beginning and ending spaces of this string.

28

static String valueOf(int value)

converts given type into string. It is overloaded.




Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer class
  • StringBuffer(): creates an empty string buffer with the initial capacity of 16.
  • StringBuffer(String str): creates a string buffer with the specified string.
  • StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
Important methods of StringBuffer class
  • public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int),append(float), append(double) etc.
  • public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
  • public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.
  • public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.
  • public synchronized StringBuffer reverse(): is used to reverse the string.
  • public int capacity(): is used to return the current capacity.
  • public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
  • public char charAt(int index): is used to return the character at the specified position.
  • public int length(): is used to return the length of the string i.e. total number of characters.
  • public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
  • public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.


Algorithm:
Part A
Start 
String s1="JAVA PROGRAM "
String s3=" WELCOME TO "
Display s1.length()
Display s1.indexOf('A')
Display s1.lastIndexOf('A'))
int start=5,end=8
char A[]=new char[end-start]
s1.getChars(start,end,A,0)
String s2=new String(A)
Display s2
A=s1.toCharArray()
i=0
while i<A.length
Display A[i]
i++
if(s1.equals(s2))
Display s1+"=="+s2
else
Display s1+"!="+s2
if(s1.equalsIgnoreCase(s1))
Display s1+"=="+s1
else
Display s1+"!="+s1
Display s1.substring(5)
Display s1.substring(9,12)
int a=s2.compareTo(s1)
Display a
Display s3=s3.concat(s1)
Display s3.trim()
Display s1.replace('A','a')
Display s1.toLowerCase()
Display s1.toUpperCase()
 
 
Same way demonstrate all StringBuffer class methods
 
Part B
Start
Take input for string s1
n=s1.length();
i=n-1
while i>=0
5.1 sb.append(s1.charAt(i));
5.2 i--
Display sb
String s2=sb.toString
if(s2.equals(s1))
Display “Palindrome"
else
Display "Not Palindrome”
Stop


Code : 
String:
package stringexample;
public class StringExample {
    public static void main(String[] args) {
        String s1=new String("Welcome to");
        String s2=new String("Java programming");
        System.out.println("The length of s1 is " + s1.length());
        System.out.println(s1.concat(s2));
        System.out.println(s2.charAt(5));
        System.out.println("The index of l in s1 is " + s1.indexOf("l"));
        char[] c1= new char[20];
         c1=s1.toCharArray();
         System.out.println(c1);
         String[] c2=new String[20];
         c2=s1.split(" ");
         for(int i=0;i<c2.length;i++){
         System.out.println(c2[i]);}
         System.out.println("the last index of o in s1 is " + s1.lastIndexOf("o"));
         int start=5,end=8;
         char A[]=new char[end-start];
         s1.getChars(start, end, A, 0);
         for(int i=0;i<A.length;i++){
         System.out.print(A[i]);}
         String s4=s1.replace('o','O');
         System.out.println("\n" +s4);
         char []c3={'W','e'};
         String s5=new String(c3);
         System.out.println(s5);
         System.out.println(s2.substring(3,6));
         System.out.println(s2.substring(3));
         System.out.println(s1.equals(s2));
         System.out.println(s1.compareTo(s5));
         String s6=" We are programmers ";
         System.out.println(s6.trim());
         System.out.println(s1.equalsIgnoreCase(s2));     System.out.println(s1.compareToIgnoreCase(s5));
         System.out.println(s2.endsWith("ing"));
    }
}
 
StringBuffer:
import java.io.*; 
public class StringBufferEx {
 
    public static void main(String[] args) 
    { 
        StringBuffer s = new StringBuffer("Java Programming"); 
        int p = s.length(); 
        int q = s.capacity(); 
        System.out.println("Length of string GeeksforGeeks=" + p); 
        System.out.println("Capacity of string GeeksforGeeks=" + q); 
        System.out.println(s.append(" for me"));
        System.out.println(s.append(1));
        System.out.println(s.insert(5, "and"));
        System.out.println(s.delete(5, 9));
        System.out.println(s.deleteCharAt(10));
        System.out.println(s.replace(0, 5, "Fast"));
        System.out.println(s.charAt(9));
        char c1[]=new char[20];
        s.getChars(0, 6,c1 ,0);
        for(int i=0;i<c1.length;i++){
            System.out.print(c1[i]);
        }
        StringBuffer s2=new StringBuffer("DaD");
        StringBuffer s3 = s2.reverse();
        if(s2.equals(s3)){
            System.out.println("\n" +s2 + " is palindrome");
        }
        System.out.println(s2.indexOf("D"));
        System.out.println(s2.lastIndexOf("D"));
        s2.setCharAt(0, 'M');
        System.out.println(s2);
        String s4= s.substring(6);
        System.out.println(s4); 
    } 


Output: 
String : 
demonstrate all String and StringBuffer class methods

StringBuffer:
demonstrate all String and StringBuffer class methods


Observations and learning: 
Ans : We saw two classes String and StringBuffer which are defined in the javalang package and imported automatically. We saw various methods of the String class and also the StringBuffer Class .StringBuffer extends the String class hence all the methods of String class are available in the StringBuffer class and we can use them.
 
Conclusion: 
Ans : We can thus conclude that the StringBuffer and the String are the two classes in java hence Strings in java are objects. Hence we can use various methods of these classes which are defines in the java lang String package for efficient codes and programms. 

Question of Curiosity :

1. What is String in Java? String is a data type?
Ans:A String in Java is actually a non-primitive data type, because it refers to an object. The String object has methods that are used to perform certain operations on strings.
 
2. What are different ways to create String Object?
Ans :
1:String s=new String(“Welcome”);
2:String s=”Welcome”;
 
3. Write a method to check if input String is Palindrome?
Ans:void palindrome(StringBuffer s1){
StringBuffer s2=s1.reverse();
if(s1.equals(s2))
{System.out.println(s1 + “ is a palindrome”);}
Else
{System.out.println(s1 + “is not a palindrome”);}}
 
4. Write a method that will remove given character from the String?
Ans:void Remove(StringBuffer s){
System.out. println(deleteCharAt(10);}
 
5. How can we make String upper case or lower case?
Ans: We can make a String to uppercase by using the toUpperCase method and to lower case by using the toLowercase method.  
 
 
6. What is String subSequence method?
Ans:The Java.lang.String.subquence() is a built-in function in Java that returns a CharSequence. CharSequence that is a subsequence of this sequence. The subsequence starts with the char value at the specified index and ends with the char value at (end-1). The length (in chars) of the returned sequence is (end-start, so if start == end then an empty sequence is returned.
 
7. How to compare two Strings in java program?
Ans: We can compare two strings in java program by using the equals to method.
 
8. How to convert String to char and vice versa?
Ans:We can convert string to character array by using the toCharArray() method. We can also do this by getChar method.
 
9. How to convert String to byte array and vice versa?
Ans:We can convert byte to string by using the method Base64.getDecoder().decode(string);and String to byte by the method getBytes();
 
10. Can we use String in switch case?
Ans:Yes we can use Strings in switch case but the case in also important.
 
Similar Programs
  1. Write a program to count number of words digits and vowels.
  2. Write a program for sorting the list of Strings.
  3. Write a program to Reverse Letter in Each Word of the Entered String.
  4. Write a program to Encode a String and Display Encoded String !
  5. Write a program to delete all occurrences of Character from the String.
  6. Write a program to Concatenate Two Strings. 
  7. Write a program to Find Substring of String. 
  8. Write a program to Compare Two Strings. 


Comments