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).

Wednesday, September 4, 2019

Creating a Vector Student with their name.

Add, Remove & Display student name from Vector

Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
·        Vector is synchronized.
·        Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program.
Following is the list of constructors provided by the vector class.
Vector( )
n  creates a default vector, which has an initial size of 10.
Vector(int size)
n  creates a vector whose initial capacity is specified by size
Vector(int size, int incr)
n  creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward
Vector(Collection c)
creates a vector that contains the elements of collection c.
Vector defines three protected data member:
§  int capacityIncreament: Contains the increment value.
§  int elementCount: Number of elements currently in vector stored in it.
§  Object elementData[]: Array that holds the vector is stored in it.
Methods of Vector class
·         addElement(Object)
Adds the specified component to the end of this vector, increasing its size by one.
·         capacity()
Returns the current capacity of this vector.
·         clone()
Returns a clone of this vector.
·         contains(Object)
Tests if the specified object is a component in this vector.
·         copyInto(Object[])
Copies the components of this vector into the specified array.
·         elementAt(int)
Returns the component at the specified index.
·         elements()
Returns an enumeration of the components of this vector.
·         ensureCapacity(int)
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
·         firstElement()
Returns the first component of this vector.
·         indexOf(Object)
Searches for the first occurence of the given argument, testing for equality using the equals method.
·         indexOf(Object, int)
Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method.
·         insertElementAt(Object, int)
Inserts the specified object as a component in this vector at the specified index.
·         isEmpty()
Tests if this vector has no components.
·         lastElement()
Returns the last component of the vector.
·         lastIndexOf(Object)
Returns the index of the last occurrence of the specified object in this vector.
·         lastIndexOf(Object, int)
Searches backwards for the specified object, starting from the specified index, and returns an index to it.
·         removeAllElements()
Removes all components from this vector and sets its size to zero.
·         removeElement(Object)
Removes the first occurrence of the argument from this vector.
·         removeElementAt(int)
Deletes the component at the specified index.
·         setElementAt(Object, int)
Sets the component at the specified index of this vector to be the specified object.
·         setSize(int)
Sets the size of this vector.
·         size()
Returns the number of components in this vector.
·         toString()
Returns a string representation of this vector.
·         trimToSize()
Trims the capacity of this vector to be the vector's current size.

Algorithm:
  1. start
  2. create an object of Vector class
  3. add five student names to Vector using addElement() method of Vector class
  4. select option from menu
  5. if option is , then add new student name to Vector using addElement() method of Vector class
  6. if option is 2, then remove specific element from Vector using removeElement() method of Vector class
  7. if option is 3, then display all Vector elements using Enumeration class methods nextElement() and hasMoreElements().
  8. stop

   Program :-

import java.util.Vector;
import java.util.*;

class c
{
public static void main(String[] args) throws Exception
{
Scanner s = new Scanner(System.in);
Vector  v=new Vector  ();
 int i,j=0,n;
do
{
System.out.println("enter choice"+"\n1. Add"+"\n2. Remove"+"\n3. Display" +"\n4. Exit");
n=s.nextInt();
switch(n)
{
case 1:System.out.println("enter name of student");
          v.add(j,s.next());
          System.out.println("==================\n");
        j++;
          for(i=0;i<v.size();i++)
          {
          System.out.println((i+1)+" "+v.get(i));
          }
          System.out.println("");   
          break;
case 2:System.out.println("enter the no of Student ");
          v.remove((s.nextInt()-1));
          System.out.println("==================\n");
       for(i=0;i<v.size();i++)
       {
       System.out.println((i+1)+" "+v.get(i));
       }
          System.out.println(""); 
       break;
case 3:System.out.println("==================\n");
          for(i=0;i<v.size();i++)
       {
       System.out.println((i+1)+" "+v.get(i));
       }
          System.out.println(""); 
       break;
}      
}while(n!=4);
}
}


Output:-

enter choice
1. Add
2. Remove
3. Display
4. Exit
1
enter name of student
Chetan
==================

1 Chetan

enter choice
1. Add
2. Remove
3. Display
4. Exit
1
enter name of student
Mayank
==================

1 Chetan
2 Mayank

enter choice
1. Add
2. Remove
3. Display
4. Exit
2
enter the no of Student
2
==================

1 Chetan

enter choice
1. Add
2. Remove
3. Display
4. Exit
==================


        Observations :-
Here we observed that how child class inherit  methods and properties of parent class.

Conclusion:
We implemented different types of Inheritance.