Wednesday, May 12, 2010

String Class in Java


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);
 }
}

0 comments:

Post a Comment

Stats

ලාංකීය සිතුවිලි

lankeeya sithuwili

Blog Catalogs

 

Let's Learn Java API. Copyright 2010 All Rights Reserved