String Class in Java
String Class in Java
String is a sequence of characters. In java, objects of String are immutable which means constant
and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “welcome”;
"Goodmorning".length(); // returns 11
3. String substring (int i): Return the substring from the ith index character to end.
4. String substring (int i, int j): Returns the substring from i to j-1 index.
5. String concat( String str): Concatenates specified string to the end of this string.
String s1 = ”Good”;
String s2 = ”morning”;
6. int indexOf (String s): Returns the index within the string of the first occurrence of the
specified string.
8. int lastIndexOf( String s): Returns the index within the string of the last occurrence of
the specified string.
9. boolean equals( Object otherObj): Compares this string to the specified object.
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or
lowercase).
14. String toLowerCase(): Converts all the characters in the String to lower case.
15. String toUpperCase(): Converts all the characters in the String to upper case.
16. String trim(): Returns the copy of the String, by removing whitespaces at both ends. It
does not affect whitespaces in the middle.
17. String replace (char oldChar, char newChar): Returns new string by replacing all
occurrences of oldChar with newChar.
String s1 = “foodmorninf“;
StringBuffer is a peer class of String that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences while StringBuffer represents
growable and writable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to
the end. It will automatically grow to make room for such additions and often has more characters
preallocated than are actually needed, to allow room for growth.
Methods
Some of the most used methods are:
StringBuffer append() method
The append() method concatenates the given argument with this string.
class StringBufferExample{
public static void main(String args[]){
} }
System.out.println(sb);//prints JavaHello
}}
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
} }
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
} }
StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}