Thursday, September 5, 2019

String and StringBuffer Class

Demonstration of all String and StringBuffer class methods Writing a program to reverse a string and check it is palindrome or not.


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:
1.      By string literal
2.      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 StrigBuffer class methods

Part B
1.      Start
2.      Take input for string s1
3.      n=s1.length();
4.      i=n-1
5.      while i>=0
5.1 sb.append(s1.charAt(i));
5.2 i--
6.      Display sb
7.      String s2=sb.toString
8.      if(s2.equals(s1))
8.1  Display “Palindrome"
else
8.2  Display "Not Palindrome”
9.      Stop.



PROGRAM :-


import java.util.Scanner;


class string
{
public static void main(String args[])
{
 Scanner sc=new Scanner(System.in);
 String name,rev ="";
 String str ="java";
StringBuffer sb=new StringBuffer("Hello "); 

System.out.println(str.length());

System.out.println(str.replace('a','A'));

System.out.println(str.toLowerCase());

System.out.println(str.toUpperCase());

sb.insert(0,"dips");                                                   
System.out.println(sb);                                    

sb.append("bye");                                           
System.out.println(sb);                                 

sb.delete(1,2); 
System.out.println(sb);                                  

sb.reverse(); 
System.out.println(sb);          

System.out.println("enter a string");
name=sc.nextLine();

int len=name.length();
for( int i=len-1;i>=0;i--)
{
rev=rev+name.charAt(i);
}

System.out.println(rev);

if (name.equals(rev))
{
System.out.println(name+ " is palindrome");
}
else
{
System.out.println(name+  " is not a palindrome");
}                      
}
}



OUTPUT :- 

 4
jAvA
java
JAVA
dipsHello
dipsHello bye
dpsHello bye
eyb olleHspd
enter a string


Observations and Learning :-

Learned how to implement String and String Buffer class and its methods Observed the output of various method of string and string buffer methods And also learned how to reverse the string and check the given string is palindrome or not.

Conclusion:

 By using method of string class and String buffer class we solved the given problem (String class method execution, stringbuffer class method execution, reverse the given string and checking wither string is palindrome or not).

No comments:

Post a Comment