Wednesday, April 4, 2012

JAVA Programming : String Class

JAVA String 

In Java there is eight primitive data type and also a special String class in java.lang.string package for string handling.
String are like sequence of characters. String is not a primitive data type (because strings are objects) but the java language provides some special support to strings so, sometimes its seems like Strings are one of the primitive type.
String are very widely used in java and if you ever done some programming in Java than you must have created  a string in some way or the other.
For example the most direct way to create an String object is by just enclosing some characters in double quotes("").

    String str ="This is a String";    

String is an object in java so it can also be declared as any other object is declared using new keyword.

      String str = new String();     

String class has several constructors to create a String object. The above example is one of the way simplest way to create an string. The constructor used in the example is a no argument constructor or we can say a default constructor which will create a empty String i.e. str will be an instance of String with no character in it.
Below is an example which show a number of ways to create a String object.

public class StringExample {
  public static void main(String[] args) {
    // this is will create an empty String
    String str = new String();

    // Creating a String using an character array
    char ch[] 'J''a''v''a''C''o''d''e''S''p''o''t' };
    String strChar = new String(ch);

    // Creating a String from character array's subarray
    //in arguments give the source character array, 
    //starting point and number of character after that
    String strSubChar = new String(ch, 44);

    //Creating an array using byte array of ASCII Value
    byte b[] ={74,65,86,65};

    String strByte = new String(b);

    //Just like character array we can also create 
    //string form subarray of byte array
    String strByteSub = new String(b,2,2);


Output of Program:

There are some more String Constructors but we will discusses them in later tutorials.

Methods of String Class:- String class provides several methods for string manipulation and these are going to be very useful in many situation like Input validation, text analysis and file conversions etc. In this tutorial we are going to discuses most of the common methods of String class.
  • public charAt(int index) :-  
  • public int length() :-
  • public String concat(String s) :-
  • public boolean equals(String s)
  • public boolean equalsIgnoreCase(String s)
  • public String substring(int begin)
  • public String substring(int begin,int end)
  • public String toLowerCase()
  • public String toUpperCase()
  • public String trim()
  • public int indexOf(int ch)
  • public int indexOf(int ch, int startIndex)
  • public int indexOf(String str)
  • public int indexOf(String str, int startIndex)