Sunday, 7 December 2014

WAP splitting a string

//Strsplit.java
class  Strsplit
{
public static void main(String[] args)
{
//take a string which is to be broken
String str="Hello, this is a book on java";

//declare a string type array s to store pieces
String s[ ];
//split the string where where a space is found in str
s=str.split(" ");

//displaying the pieces from s
for(int i=0; i<s.length; i++)
System.out.println(s[i]);
}
}

WAP which will help us to understand how to create strings and how to use some important methods of String class.

//StrDemo.java
class StrDemo
{

public static void main(String[] args)
{
// creating string in 3 ways
String s1="The book on java";
String s2=new String(" i like it");
char arr[]={ 'D','r','e','a','m','t','e','c','h'};
String s3=new String(arr);
///Display all the three string
 
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);

       // find length of first string
   
System.out.println("Length of S1 ="+s1.length());

       //concatinate two strings

System.out.println("s1 and s2 joined ="+s1.concat(s2));
   
       //concatinate three strings with +
    System.out.println(s1+ " from "+s3);

// test if string s1 starts with A
             boolean x=s1.startsWith("A");

if(x)
        System.out.println("s1 starts with \'A\' ");
               else
         System.out.println("s1 does not starts with \'A\' ");
               
//extract substring from s2, starting from 0th chat to 6th char

String p =s2.substring(0,7);
                 System.out.println(p);

//extract substring from s3, starting from 0th char to 8th char
 
   String q=s3.substring(0,9);
                System.out.println(q);

//concatenate the strings p and q
System.out.println(p +" "+q);

//convert s1 in to upper cast and lower cast

                System.out.println("Upper s1= "+s1.toUpperCase());
                System.out.println("Lower s1= "+s1.toLowerCase());


   
}
}

Copying a string into an array

//Strcpy.java
class  Strcpy
{

public static void main(String[] args)
{
   String str="Hello, this is a book on java";
char arr[]=new char[20];

//copy from str into arr starting from 7th char to 20 char

str.getChars(7,21,arr,0);
System.out.println(arr);
}
}

String comparison using ==

//Strcompare.java

import java.util.Scanner;
class  Strcompare
{
public static void main(String[] args)
{
Scanner scn=new Scanner(System.in);
        System.out.println("Enter  first String");
String s1=scn.nextLine();

System.out.println("Enter second Number");
        String s2=scn.nextLine();

       if (s1.equals(s2))
        System.out.println("Both are same");
  else
System.out.println("Not same");
         
}
}

WAP to search for a given string in an array of strings.This is achieved by comparing the searching string with each of the array elements one by one in a loop.

//Search.java
import java.io.*;
class  Search
{
public static void main(String[] args) throws Exception
{
//to accept data from key board
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many String ??");
int n=Integer.parseInt(br.readLine());
   
   //create a string type array with size n
String str[]=new String[n];

//store string in to str[]
for(int i=0; i<n; i++)
{
          System.out.println("Enter a string");
str[i]= br.readLine();
}

//accept  the string to search
System.out.println("Enter a string to search");
String search= br.readLine();

//take a boolean var.
boolean found = false;

//search for the string in str[]
for(int i=0; i<n; i++)
{
   if (search.equalsIgnoreCase(str[i]))
  {
              System.out.println("Found at Position : "+(i+1));
found = true; //string found

   }
}
//if not found , display message
if(!found)
System.out.println("Not found in the array");
}
}

WAP to test the immutablility of strings

//Test.java
class  Test
{
public static void main(String[] args)
{
String s1 ="data";
String s2="base";

//join s1 and s2 and store in s1
s1=s1+s2;
System.out.println(s1);
}
}

/*And the output of the program is "database" .It seems that the string s1 content is modified.
 Earlier s1 got "data" and s2 had "base". After s1+s2 they are joined and the total string
 becomes "database". This string is assigned to s1 again. So s1 appears to be mutable.
  But we learned that strings are immutable.

  s1 is definitly immutable. But then why the output of the program is like that ?In the program,
  jvm creates two object s1 and s2 separately. when s1+s2 is done, jvm creates a new object
  and stores the string "database" in that object.But it does not modify the contents of the string s1.
  After creating the new object, the reference s1 is adjusted to refer to that new object. The point
  we should observe here that the contents of the string s1 are not modified.this is the reason
  , strings are called immutable .the old object that contains "data" has lost its reference .so it is
  called a 'unreferenced object' and garbage collector will remove it from memory.

WAP to test whether a string is palindrome or not

//Palindrome.java
import java.io.*;

class Palindrome
{
public static void main(String[] args) throws IOException
{
//accept the string from keyboard
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string : ");
String str=br.readLine();

//store a copy of original string in temp
        String temp =str;

//convert the string in to stringBuffer
StringBuffer sb = new StringBuffer(str);

//now reverse the string in stringBuffer
// sb.reverse();
        System.out.println(sb.reverse()+" after reverse");

//convert the stringbuffer in string
  str= sb.toString();

//compare the original string  available in temp with this reversed string

if(temp.equalsIgnoreCase(str))
 System.out.println(temp+" is palindrome");
else
   System.out.println(temp+" is not palindrome");
}
}

WAP to learn how to use some of StringBuffer class method

//Full.java
import java.io.*;

class Full
{
public static void main(String[] args) throws IOException
{
//create empty string buffer object
StringBuffer sb= new StringBuffer();

//to accept data from keyboard
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

//Accept surname
System.out.println("Enter surname : ");
String sur = br.readLine();

//accept middlename
 System.out.println("Enter midname ");
 String mid=br.readLine();
 
         //accept Lastname
 System.out.println("Enter lastname ");
 String last=br.readLine();

          //append sur name, mid name, lastname to sb
  sb.append(sur);
           //sb.append(mid);
  sb.append(last);
 
          //display all the name till now
 System.out.println("Name= "+sb);
 
         //insert mid name after sur name in sb

 int n = sur.length();
 sb.insert(n,mid);
 //display full name
 System.out.println(" Full Name= "+sb);

 //reverse and display the name
  System.out.println("In reverse = "+sb.reverse());


}  
}

Wednesday, 8 October 2014

Difference Between String , StringBuilder and StringBuffer


String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  . 
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed .

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable            
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string  

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe . 

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value .
String Buffer can be converted to the string by using 
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe .  


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye"); 
// Above statement is right as it modifies the value which is allowed in the StringBuilder


--------------------------------------------------------------------------------------------------
                                    String                   StringBuffer             StringBuilder
--------------------------------------------------------------------------------------------------                 
Storage Area | Constant String Pool           Heap                       Heap 
Modifiable     | No (immutable)                  Yes( mutable )        Yes( mutable )
Thread Safe   | Yes                                     Yes                          No
 Performance | Fast                                    Very slow                Fast
----------------------------------------------------------------------------------------------------