Java is the future !: String class in Java

Saturday, October 9, 2010

String class in Java

String class in Java is final so no class can extend the String class hence method overriding is also not possible. Two strings can be concate by + opertor. That's the only overloaded operator in Java.

String str = "xyz";

is equivalent to :

char info[] = { 'x', 'y', 'z' };
String str = new String (info);

Here are some more examples of how strings can be used:

System.out.println("xyz");
String cde = "pqr";
System.out.println("xyz" + pqr);
String c = "xyz".substring(2,3);
String d = pqr.substring(1, 2);



Note : Passing a null arguement to the constructor or method in String class will throw a NullPointerException.

Most commonly used methods in String class.

1. charAt(int index)
Returns the character at the specified index.
2. compareTo(String anotherString)
Compares two strings lexicographically.
3. compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
4. compareTo(Object o)
Compares this String to another Object.
5. concat(String str)
Concatenates the specified string to the end of this string.
6. equals(Object anObject)
Compares this string to the specified object.
7. indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
8. indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
9. length()
Returns the length of this string.
10. replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
11. split(String regex)
Splits this string around matches of the given regular expression.
12. substring(int beginIndex)
Returns a new string that is a substring of this string.
13. substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
14. toCharArray()
Converts this string to a new character array.

No comments:

Post a Comment