Friday 30 December 2016

Overview Of Java String



String Overview:

  In general String is a sequence of characters. But in Java, Strings are objects that represent the sequence of characters. String objects are created by using String class. The objects of the String class are immutable, which means that, a String once created cannot be changed. If you need to change a string, you can always create a new String that contains the modifications. The original string is left unchanged. This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones. To modify or make change in String, Java provides tow option: StringBuffer and StringBuilder.

  The String, StringBuffer, and StringBuilder. classes are defined in java.lang. These classes are available to all programs automatically. These classes are declared final, which means that none of these classes may be sub classed.

 The String Constructors:

  create String, String class supports several constructors. To create an empty String, we call the default constructor. For example:

String s = new String();//instance of String with no characters in it.

  To create a string with characters java provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ]);

  Here is an example:

char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);

  This constructor initializes s with the string “abc”.

  You can construct a String object that contains the same character sequence as another String object using this constructor:

String(String strObj)

 String Example:

// Construct one String from another.
class MakeString
{
  public static void main(String args[])
  {
    char c[] = {'J', 'a', 'v', 'a'};
    String str1 = new String(c);
    String str2 = new String(str1);
    System.out.println(str1);
    System.out.println(str2);
  }
}

  The output from this program is as follows:

Java
Java


0 comments:

Post a Comment

Powered by Blogger.

Stats