Describe Java string class. Explain methods of Java string class. Explain the characteristics of StringBuffer class
String Class1. The String class is immutable.
2. The contents of the String object can not be changed.
3. String class is final class. That implies it can not have sub classes.
4. String objects can be concatenated by using + and += operators
Following are the examples to create String class objectsString city1 = “Bangalore”;
String city2 = “Mumbai”;
String city3 = “New Delhi is the “ + “Capital of India”;
String name = “Fedrick”;
String str4 = “My name is” + name;
String str5 = new String(“My name is Jones”);
Methods of String classAccessor Methods1. length() – To find the number of characters of a string
2. charAt(index) – Returns the character a the given index
3. split(string,delimiter) – Splits the at every delimiter and returns a String array
4. substring(start[,endindex]) – Returns all the characters from start upto but not including endindex
Modifier Methods1. concat(string) : Returns a new string after concatenating str to the original string. The original string remain unchanged.
2. replace(charwith, charreplacement) : Replaces charwith with charreplacement and returns a new string.
Boolean test methods1. endsWith(strend) : Returns true, if the string ends with strend
2. equals(str) : Returns true, if the string and str are equal
3. equalsIgnoreCase(str) : Returns true, if the string and the str are equal irrespective of case sensitivity
4. startsWith(strbeg) : Returns true, if the string starts with strbeg
Inter test methods1. compareTo(str) : Returns 0 if str equals with the object, -1 if object is before parameter in sort order and +1 if otherwise
2. indexOf(substr) : Returns the position of the first occurrence of a substring in the given string
3. length() : Returns the number of characters in the string
StringBuffer1. StringBuffer class is mutable class.
2. The StringBuffer object contents can be changed
3. The object can be changed dynamically
4. They are preferable when heavy modifications are demanded by the application
5. To compare StringBuffer object with equals() method, the object need to be converted into String class, as the StringBuffer class does not override the equals() method.