You are on page 1of 10

More about String class * String is a class in java * String can store alpha-numeric and special characters * String

can store huge data upto ( 128k might vary based on jdk version ) * String class comes with many string processing functions Declaration String s; or String x = new String( ); Assignment s = "welcome to java programming" String initialization String s = "Hello world"; Finding string length String s = "google map"; int n = s.length();

(10) Case conversion functions String s = "google map"; s.toUpperCase(); // no effect on value stored in "s" immutable s = s.toUpperCase(); or String x = s.toUpperCase(); "s" remains same , "x" stored with uppercase s = s.toLowerCase(); Finding substring in a string s = "reach2cp@yahoo.co.in"; int p = s.indexOf("yahoo"); (9) "s" gets modified

int p = s.indexOf("h"); (4) int p= s.indexOf("india"); (-1) int p = s.lastIndexOf("h"); (11) int p = s.indexOf("cp" , 10 ); search for substring "cp" from 10 position instead of 0 int p =s.indexOf("c" , 10 ); 15 Extracting substring String s = "google indian map" String x = s.substring( 7 , 10 ) | "ind"

String x = s.substring( 7 ); | "indian map" Checking for leading and trailing characters String s = "http://www.yahoo.com" boolean r = s.startsWith("http"); | true s.startsWith("HTTP") s.startsWith("httpd") s.startsWith("h") s.endsWith(".com") s.endsWith("COM") Extracting character from a string String s = "sunlight" s[0] s[1] - 's' - 'u' <= GOES wrong false false true true false

s[2]

- 'n'

char c = s.charAt( 0 ) 's' for(int i=0; i<s.length(); i++ ) { char c = s.charAt(i) . . } String comparsion String s , r; . . if( s.equals( r ) ) if same function return value true case will be considered during match if( s.equalsIgnoreCase( r ) ) compare by ignoring case Split function

String s = "google,yahoo,rediff,indiatimes" String v [ ] = s.split(","); v[0] - google v[1] - yahoo v[2] - rediff v[3] - indiatimes v.length - 4 elements) v[3].length( ) - 10 characters Ascii based comparsion String s = "local" String r = "loyal" int p = s.compareTo( r ); 'c' - 'y' ascii difference of 'c' - 'y' will be stored in "p" String "replace" (No. of

String s = "google is best,google is simple" s = s.replaceAll( "google", "yahoo"); | yahoo is best,yahoo is simple s = s.replaceFirst( "google", "yahoo"); | yahoo is best,google is simple String to Number conversion: String s = "456" int i = Integer.parseInt( s ); | 456 int a = 761; String s = String.valueOf( a ); | "761" String concat

String s = "spike" String r = "buster" s = s.concat( r ); | spikebuster s = "you are right" boolean v = s.matches("write"); | true Removing white space( blank space ) [ leading and trailing only ] String s = " good " String r = "good" if ( s.equals( r ) ) ==> false

if( s.trim().equals( r.trim() ) ) => true

You might also like