Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

String Class in Java

Tags: string

String objects contain sequence of charters. Strings can be concatenate using ( + ) operator which is a special java language feature. String class represent a string using UTF -16 (unicode character representation in java)   
There are different constructors available in Java we have to select the most suitable construct for our purpose. (Click here to see the constructor summary)
Following methods are available in the String class.
length()

charAt(int index)
compareTo(String str)
compareToIgnoreCase(String str)
concat(String str)
endsWith(String suffix)
equals(Object obj)
equalsIgnoreCase(String str)
indexOf(String str)
lastIndexOf(String str)
replace(char oldChar,char newChar)
split(String regex)
startsWith(String prefix)
substring(int beginIndex)
trim(String s)
Lets see some example written to demonstrate the above methods.
Compare the code with given output.
 
//© http://imagocomputing.blogspot.com/ 
class StringDemo {
public static void main(String args[]){
String str1="Sri Lanka is the most beautiful country";
String str2="Java is a OOP language";
System.out.println("Length of str1 : " + str1.length());
System.out.println(str1.compareTo(str2));
System.out.println(str1.endsWith("try"));
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.indexOf("Lanka"));
System.out.println(str1.lastIndexOf("t"));
String newStr=str2.replace("J","L");
System.out.println("Replaced string : " + newStr);
System.out.println(str1.startsWith("Sri"));
String subStr=str1.substring(22);
String beforeTrim=" Hello Sri Lanka ";
String afterTrim=beforeTrim.trim();
System.out.println("Before trim : " + beforeTrim);
System.out.println("Aftre trim : " + afterTrim);
}
}


This post first appeared on Let's Learn Java API, please read the originial post: here

Share the post

String Class in Java

×

Subscribe to Let's Learn Java Api

Get updates delivered right to your inbox!

Thank you for your subscription

×