Pages

Saturday, 25 August 2012

String Class in Java

A String is a sequence of character. It is one of most powerful class in java. String object is immutable, It means once you created a string object, Changes to it's contents or length is not possible.
Most frequent way of creating String object is..

String str = "Hello Java";
Here, "Hello Java" is called string literal. When we use String class in our program we should know few points about String in java.
  1. String consist of sequence of characters. Each character in String is a 16-bit Unicode character.
  2. "+" Operator is overloaded for String class and hence it can be use for concatenate to Strings in java, For Example

         String str = "Hello"+" Java";
  3. In java a String can be created from a byte array, character array, from existing String, from StringBuffer, or from literal as shown above, Java provides a wide range of constructor for all these.
  4. Every class has a method i.e toString() to provide string representation of it's object.
  5. String index is start with 0.   

Note:- 

  • String object is not an array of characters. 
  • String object is immutable; its reference variable is not.

 

Constructors in String class:-

 

String class has several constuctors. some of them we discuss here.

  • To ceate a String object from literals we can do this.
               String str = "Welcome";

  • To create a empty String call it's default constructor. For example.
               String str = new String();

  • To create a String object from a character array we can use following form of constructor
                String(char[] values); 

                For example.....
                    char[] data = {'a', 'b', 'c', 'd', 'e'};
                    String str = new String(data);
                By this constructor, A String will be created having string value "abcde".

  • To create a String object from a byte array we can use following form of constructor
                String(byte[] values); 

                For example.....
                     byte[] data = {65, 66, 67, 68, 69, 70};
                    String str = new String(data);
                By this constructor, A String will be created having string value "ABCDE".

  • To create a String from StringBuffer we can use following form of constructor
                String(StringBuffer buffer);

                For example...
                     StringBuffer buffer = new StringBuffer();
                             buffer.append('a');
                             buffer.append("bcd");
                     String str = new String(buffer);
                By this consturctor, A String will be created having string value "abcd".

  •   To create a String from existing String, we can use following form of constructor
                   String(String str);

                   For example....
                        String s1 = "Hiiii Java";
                        String s2 = new String(s1); 
  • To create a subrange of an character array as an input for making String, we can use following form of constructor

          String(char[] values, int starIndex, int numChars);
      Here startIndex spedifies the index at which the subrange begins, and numChars specifies the number of charectrer to use

          For example.....
               
    char[] data = {'a', 'b', 'c', 'd', 'e', 'f', 'g',' h'};
                String str = new String(data, 2, 3);
         By this this constructor, A String will be created having string value "cde".
              

Methods in String class:-
  • String concat(String str) 
          Concatenates the specified string to the end of this string.

  • char charAt(int index)
         Returns the character at the specified index.

  • boolean endsWith(String value) 
        Tests if this string ends with the specified value.

  • boolean equals(Object object)
        Compares this string to the specified object.

  • boolean equalsIgnoreCase(String object)
        Compares this String to object, ignoring case considerations.

  • int indexOf(String str, int fromIndex)
         Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

  • int indexOf(String str)
         Returns the index within this string of the first occurrence of the specified substring.

  • int indexOf(int ch, int fromIndex)
         Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.


  • int indexOf(int ch)
       Returns the index within this string of the first occurrence of the specified character.
 
  • int lastIndexOf(int ch)
       Returns the index within this string of the last occurrence of the specified character.

  • int lastIndexOf(int ch, int fromIndex)
      Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

  • int lastIndexOf(String str)
      Returns the index within this string of the rightmost occurrence of the specified substring.

  • int lastIndexOf(String str, int fromIndex)
      Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

  • int length()
      Returns the length of this string.

  • String replace(char oldChar, char newChar)
      Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

  • String replaceAll(String regex, String replacement)
      Replaces each substring of this string that matches the given regular expression with the given replacement.

  • String replaceFirst(String regex, String replacement)
      Replaces the first substring of this string that matches the given regular expression with the given replacement.

  • String[] split(String regex)
     Splits this string around matches of the given regular expression.

  • boolean startsWith(String prefix)
     Tests if this string starts with the specified prefix.

  • boolean startsWith(String prefix, int toffset)
     Tests if this string starts with the specified prefix beginning a specified index.

  • CharSequence subSequence(int beginIndex, int endIndex)
     Returns a new character sequence that is a subsequence of this sequence.

  • String substring(int beginIndex)
      Returns a new string that is a substring of this string.

  • String substring(int beginIndex, int endIndex)
      Returns a new string that is a substring of this string.

  • char[] toCharArray()
     Converts this string to a new character array.

  • String toLowerCase()
     Converts all of the characters in this String to lower case using the rules of the default locale.
  •   String toLowerCase(Locale locale)
     Converts all of the characters in this String to lower case using the rules of the given Locale.
  • String toUpperCase()
     Converts all of the characters in this String to upper case using the rules of the default locale.

  • String toUpperCase(Locale locale)
    Converts all of the characters in this String to upper case using the rules of the given Locale.

  • String trim()
     Returns a copy of the string, with leading and trailing whitespace omitted.

  • String toString()
This object (which is already a string!) is itself returned.

Friday, 27 July 2012

Serialization in Java

Serialization is a process of writing the state of an object to disk in the form of file. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in program. But when we use serialization, the few points we should keep in mind,

  1. Only that object of class can be serialized which impliments  java.io.Serializable interface.      
  2.  In the process of serialization all member of the class has been serialiazed. If we want to prevent serialization of any member from a class we need to declare it transient. It is a special keyword in java which is used to prevent serialization of member.
  3. static members of the class has not been serialized. A member class(A class which defined inside a class as a member of  outer class) which if declared static can not be serialized. 
  4. In java, array of any type can be also serialized because java treated array as an object.
  5. Primitive data types can not be serialized.

How do we use serialization?

There are two high-level classed which is used to perform serialization, ObjectInputStream and ObjectOutputStream.

The ObjectOutputStream class contains many write methods for writing objects into streams, but one method in particular important that we will use in our example :
public final void writeObject(Object x) throws IOException
 
The ObjectInputStream class contains read method for reading objects from stream, one of them is show here,
 public final Object readObject() throws IOException,
ClassNotFoundException 
 
The return type of this method is Object so we will need to cast it to its appropriate data type.
 
Example of Serialization:- 
 

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * @author Saurav Gupta
 *
 */

public class SerializationTest {
 public static void main(String[] s) {
  String str = "Hello Java";
  try {
    FileOutputStream fOut= new FileOutputStream("data.ser");
    ObjectOutputStream outStream = new ObjectOutputStream(fOut);

           outStream.writeObject(str);
           outStream.close();

        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}
 
Example of Deserialization:- 
 
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * @author Saurav Gupta
 * 
 */

public class DeserializationTest {
  public static void main(String[] s) {
    try {
        FileInputStream fIn = new FileInputStream("data.ser");
        ObjectInputStream inStream = new ObjectInputStream(fIn);

        String str = (String) inputStream.readObject();
        System.out.println(str);

      } catch (Exception e) {
            e.printStackTrace();
      } 
   }
}