STRING METHODS IN JAVA
String is a sequence of characters. In java, objects of string are immutable which means a constant and cannot be changed once created.
Creating a String:
➢ String literal
String s = “welcome”;
➢ Using new keyword
String s = new String (“welcome”);
Example:
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by
new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
String Methods:
1. String concat (String str) - Concatenates calling String with str.
2. int length() - Returns length of a String
3. char char at (intindex) - Returns the character at specified location(from0)
4. int compare to (String str) - Returns a negative value if calling String is less than str,a positive Value if calling String is greater than str or 0 if Strings are equal.
5. int index of (String str) - Returns first occurrence of the String.
6. int lastIndex of (String str) - Returns last occurrence of the String.
7. String replace(char oldchar, char new char) - Returns a new String that is obtained by replacing all characters Old char in String with new char.
8. String substring (int begin Index) - Returns a new String consisting of all characters from begin Index Until the end of the String
9. String to Lower Case () - Converts all characters into lowercase
10. String to Upper Case() - Converts all characters into uppercase
11. String trim() - Eliminates a leading and trailing spaces
Example:
public class Strop
{
public static void main(String ar[])
{
String s="Welcome";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);
}
}
Output:
WELCOME
Welcome
Welcome