String handling in java
In this topic we discuss about the string handling or string manipulation. Many operation can be done with string (s) like string comparison, concatenation, sub-string etc.
1. What is String ?
String is basically a sequence of characters. In java, the string is an object and it is in the java.lang package.
2. Feature of String class:
a) It is a final class. So can’t be inherited.
b) String class implements Serializable, Comparable and CharSequence interfaces and extends Object class.
c) It is an immutable class.
3. How to create a String object ?
There are two ways to create a String object.
a) Using string literal.
Ex:- String str = “abc”;
b) Using new operator.
Ex:- String str = new String(“abc”);
a) String literal :
String literal is basically created by assigning the value to a string variable with in double quote. i.e
String str = “abc”;
Now we create one more string object using string literal. i.e
String str1 =”abc”;
In this case, JVM will check the string literal pool or string constant pool for this object. If it exists in the pool then JVM won’t create a new instance, a reference to the pooled instance returns. Otherwise, JVM will create a new instance in the pool.
So, only one instance will be created here and str.equals(str1) will return true. Because str and str1 both are pointing to the same memory location.
b) new operator :
String str = new String (“abc”);
In this case, JVM will create two object. One object is in the heap memory and another object is in the string constant pool.
4. Some methods of the String class:
I. public int length()
II. public boolean empty()
III. public char charAt(int index)
IV. public String toString()
V. public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
VI. public boolean equals(Object anObject)
VII. public boolean contentEquals(StringBuffer sb)
VIII. public boolean equalsIgnoreCase(String anotherString)
IX. public int compareTo(String anotherString)
X. public boolean startsWith(String prefix, int toffset)
XI. public boolean startsWith(String prefix)
XII. public boolean endsWith(String suffix)
XIII. public int hashCode()
XIV. public int indexOf(int ch)
XV. public int lastIndexOf(int ch)
XVI. public int indexOf(String str)
XVII. public String substring(int beginIndex)
XVIII. public String substring(int beginIndex, int endIndex)
XIX. public String[] split(String regex, int limit)
XX. public boolean contains(CharSequence s)
XXI. public String concat(String str)








