Java String Class Useful Methods Java by Rajesh Kumar Sahanee - August 30, 2015August 30, 20150 Post Views: 5,076 Today I am gonna explain some useful methods of String class in Java. String class is very powerful class in java which provides many useful methods to manipulate string. Strings are object in java and it is not primitive datatype. StringMethods.java Java public class StringMethods { public static void main(String args[]){ //String object created with empty string (default constructor called here) String str = new String(); //String object with "Test" value String str2 = new String("Test"); //String object created from character array (arrays are also object in java) char[] char_arr = new char[]{'C','H','A','R','A','C','T','E','R'}; String str3 = new String(char_arr); /* String object can also be created from byte array, StringBuilder object, StringBuffer object */ //length: this methods return type is int and it returns length of string System.out.println("Length of str is " + str.length()); System.out.println("Length of str2 is " + str2.length()); System.out.println("Length of str3 is " + str3.length()); System.out.println(); //isEmpty: this method returns true if string is empty and false if string has some value System.out.println("str is empty: " + str.isEmpty()); System.out.println("str2 is empty: " + str2.isEmpty()); /* 1. charAt: this method returns character at specified index, index starts from 0 2. it will throw index out of bound exception if specified index is less than 0 and greater than length of string */ System.out.println("Character at index 2 in str2 is " + str2.charAt(2)); //s /* getBytes: this method converts string to byte array it can take CharSet as parameter and CharSet can be specified using Charset object or by name of charset as string */ byte[] bytes = str2.getBytes(); for(int i=0; i<bytes.length; i++){ System.out.print("'"+ (char)bytes[i] + "' "); //typecasting from byte to char } /* equals: this method is Object class method and Overridden in String class this method compares value of string not reference */ String compstr1 = new String("TEST"); String compstr2 = new String("TEST"); System.out.println("\n"); System.out.println("Comparing String reference: " + (compstr1 == compstr2)); System.out.println("Comparing String value: " + (compstr1.equals(compstr2))); //contentEquals: this method compares string with specified character sequence and returns true if sequence are equal String compstr3 = new String(new char[]{'T','E','S','T'}); System.out.println("\ncompstr1 and compstr3 are equal: " + compstr1.contentEquals(compstr3)); //equalsIgnoreCase: this method compares string case insensitively ie String str4 = "test"; String str5 = "TEST"; System.out.println("\nTEST and test are equal: " + str4.contentEquals(str5)); System.out.println("TEST and test are equal: " + str4.equalsIgnoreCase(str5)); //compareTo: this method compares two string alphabetically System.out.println("\ncompareTo Test with Testing: "+("Test".compareTo("Testing"))); System.out.println("compareTo Testing with Test: " + ("Testing".compareTo("Test"))); /* regionMatches(int toffset, String other, int ooffset, int len): this method compares region/substring of two string toffset: starting index of first string on which this method is called other: string whose region is gonna be compared oofset: starting index of other string len: length of string it will applied on both string which is goona be compared it can also take boolean argument before toffset, if we pass true then it will compare ignoring case */ String str6 = "This is Testing"; String str7 = "Testing String"; System.out.println("\nMatching region: " + str6.regionMatches(8,str7,0,4)); /* startsWith: this function returns true if string starts with specified string it can also take starting index of sting from where to begin looking */ System.out.println("\nThis is Testing starts with This: " + str6.startsWith("This")); System.out.println("This is Testing starts with this: " + str6.startsWith("Test",8)); /* indexOf: this method gives index of specified int, string or char array in string it can also take start index from where to start finding returns -1 if not found */ System.out.println("\nIndex of 'Test' in 'This is Testing': " +str6.indexOf("Test")); System.out.println("Index of 'is' in 'This is Testing': "+str6.indexOf("is")); System.out.println("Index of 'is' in 'This is Testing' after offset 3: "+str6.indexOf("is",3)); /* lastIndexOf: this method gives last index of specified int, string or char array in string it can also take index from where to start finding, it will search from right to left returns -1 if not found */ System.out.println("\nLast Index of 'is' in 'This is Testing': " +str6.lastIndexOf("is")); System.out.println("Last Index of 'is' in 'This is Testing' before offset 4: "+str6.lastIndexOf("is",4)); /* substring: just as name suggests it gives substring from specified index to end of string or from specified begin index to specified endIndex - 1 */ String str8 = "This is Testing"; System.out.println("\nSubstring of 'This is Testing' from index 3: " + str8.substring(3)); System.out.println("Substring of 'This is Testing' from index 3 to 9: " + str8.substring(3,9)); //subsequence: this gives subsequence of string and it behaves exactly same as substring(beginIndex,endIndex) method System.out.println("Subsequence of 'This is Testing' from index 3 to 9: " + str8.subSequence(3,9)); //concat: this method combines string to specified string System.out.println("\nConcatenation: " + str8.concat(" Added at last")); /* replace: this method replaces each substring which matches first argument with second argument first argument and second argument could be char or CharSequence replaceFirst: replace: this method replaces first occurrence of substring which matches first argument with second argument replaceAll: this method replaces each substring which matches first argument with second argument */ System.out.println("\nReplacing 'T' with 'P' in 'This is Testing': " + str8.replace('T','P')); System.out.println("Replacing 'is' with 'was' in 'This is Testing': " + str8.replace("is","was")); System.out.println("Replacing first 'is' with 'was' in 'This is Testing': " + str8.replaceFirst("is","was")); System.out.println("Replacing each 'is' with 'was' in 'This is Testing': " + str8.replaceAll("is","was")); //matches: returns true if string matches the specified regular expression System.out.println("\n'This is Testing' matches 'This(.*)' regex pattern: " + str8.matches("This(.*)")); System.out.println("'This is Testing' matches '(.*)This' regex pattern: " + str8.matches("(.*)This")); /* split: splits string around matches of the specified regular expression and returns array of string it can also take int as second parameter that controls the number of times the pattern is applied and therefore affects the length of the resulting array. if second parameter is n then pattern comparison applied n - 1 times and the array's last entry will contain all input beyond the last matched delimiter */ String str9 = "This:is:test:are:you:ready"; System.out.println("\n" + str9 + " after splitting"); for(String s : str9.split(":")){ System.out.print(s + " "); } System.out.println("\n" + str9 + " after splitting with limit 4"); for(String s : str9.split(":",4)){ System.out.print(s + " "); } /* toLowerCase: converts all characters in the string to lower case toUpperCase: converts all characters in the string to upper case both method can take locale object as its argument to which it should be converted */ String upper = "TEST"; String lower = "test"; System.out.println("\n\nUpper to Lower: " + upper.toLowerCase()); System.out.println("Lower to Upper: " + lower.toUpperCase()); //trim: this method removes leading and trailing spaces from string String strwithspaces = " With Space "; System.out.println("\n'"+strwithspaces+"' after trimming: '" + strwithspaces.trim()+"'"); //toCharArray: this method converts string to character array String str10 = "ARRAY"; System.out.println("\nARRAY after converting to char array"); for(char c : str10.toCharArray()){ System.out.print("'"+c+"' "); } /* format: It is static method and returns a formatted string using the specified format string and arguments. it is similar to printf in 'C' programming language but does not print instead it gives formatted string it follows below syntax while formatting %[argument_index$][flags][width][.precision]conversion it can also take locale as its first argument */ java.util.Calendar c = java.util.Calendar.getInstance(); String s = String.format("Today is : %1$tm %1$te,%1$tY", c); String s2 = String.format("%1$.2f %.10f", 45.235485); System.out.println("\n\n" + s); System.out.println(s2); //valueOf: it is static method which converts specified parameter/value to string , parameter/value could be of any type float, double, int long, object, etc. String number1 = String.valueOf(50); String number2 = String.valueOf(5.9); System.out.println("Number 1: " + number1 + " Number 2: " + number2); /* This method returns a canonical representation for the string object. A pool of strings which is initially empty, is maintained privately by the String class. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the String.equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. */ String str11 = new String("Interned String"); System.out.println("\nInterned: " + str11.intern()); /* copyValueOf: this method returns string containing characters of specified character array it can also return string that contains the characters of the subarray of the specified character array, by taking offset and length of subarray */ char[] carr = new char[]{'C','H','A','R','A','C','T','E','R'}; System.out.println("\nCopied value from character array: " + String.copyValueOf(carr)); System.out.println("Copied subarray from character array: " + String.copyValueOf(carr,0,4)); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203 public class StringMethods { public static void main(String args[]){ //String object created with empty string (default constructor called here) String str = new String(); //String object with "Test" value String str2 = new String("Test"); //String object created from character array (arrays are also object in java) char[] char_arr = new char[]{'C','H','A','R','A','C','T','E','R'}; String str3 = new String(char_arr); /* String object can also be created from byte array, StringBuilder object, StringBuffer object */ //length: this methods return type is int and it returns length of string System.out.println("Length of str is " + str.length()); System.out.println("Length of str2 is " + str2.length()); System.out.println("Length of str3 is " + str3.length()); System.out.println(); //isEmpty: this method returns true if string is empty and false if string has some value System.out.println("str is empty: " + str.isEmpty()); System.out.println("str2 is empty: " + str2.isEmpty()); /* 1. charAt: this method returns character at specified index, index starts from 0 2. it will throw index out of bound exception if specified index is less than 0 and greater than length of string */ System.out.println("Character at index 2 in str2 is " + str2.charAt(2)); //s /* getBytes: this method converts string to byte array it can take CharSet as parameter and CharSet can be specified using Charset object or by name of charset as string */ byte[] bytes = str2.getBytes(); for(int i=0; i<bytes.length; i++){ System.out.print("'"+ (char)bytes[i] + "' "); //typecasting from byte to char } /* equals: this method is Object class method and Overridden in String class this method compares value of string not reference */ String compstr1 = new String("TEST"); String compstr2 = new String("TEST"); System.out.println("\n"); System.out.println("Comparing String reference: " + (compstr1 == compstr2)); System.out.println("Comparing String value: " + (compstr1.equals(compstr2))); //contentEquals: this method compares string with specified character sequence and returns true if sequence are equal String compstr3 = new String(new char[]{'T','E','S','T'}); System.out.println("\ncompstr1 and compstr3 are equal: " + compstr1.contentEquals(compstr3)); //equalsIgnoreCase: this method compares string case insensitively ie String str4 = "test"; String str5 = "TEST"; System.out.println("\nTEST and test are equal: " + str4.contentEquals(str5)); System.out.println("TEST and test are equal: " + str4.equalsIgnoreCase(str5)); //compareTo: this method compares two string alphabetically System.out.println("\ncompareTo Test with Testing: "+("Test".compareTo("Testing"))); System.out.println("compareTo Testing with Test: " + ("Testing".compareTo("Test"))); /* regionMatches(int toffset, String other, int ooffset, int len): this method compares region/substring of two string toffset: starting index of first string on which this method is called other: string whose region is gonna be compared oofset: starting index of other string len: length of string it will applied on both string which is goona be compared it can also take boolean argument before toffset, if we pass true then it will compare ignoring case */ String str6 = "This is Testing"; String str7 = "Testing String"; System.out.println("\nMatching region: " + str6.regionMatches(8,str7,0,4)); /* startsWith: this function returns true if string starts with specified string it can also take starting index of sting from where to begin looking */ System.out.println("\nThis is Testing starts with This: " + str6.startsWith("This")); System.out.println("This is Testing starts with this: " + str6.startsWith("Test",8)); /* indexOf: this method gives index of specified int, string or char array in string it can also take start index from where to start finding returns -1 if not found */ System.out.println("\nIndex of 'Test' in 'This is Testing': " +str6.indexOf("Test")); System.out.println("Index of 'is' in 'This is Testing': "+str6.indexOf("is")); System.out.println("Index of 'is' in 'This is Testing' after offset 3: "+str6.indexOf("is",3)); /* lastIndexOf: this method gives last index of specified int, string or char array in string it can also take index from where to start finding, it will search from right to left returns -1 if not found */ System.out.println("\nLast Index of 'is' in 'This is Testing': " +str6.lastIndexOf("is")); System.out.println("Last Index of 'is' in 'This is Testing' before offset 4: "+str6.lastIndexOf("is",4)); /* substring: just as name suggests it gives substring from specified index to end of string or from specified begin index to specified endIndex - 1 */ String str8 = "This is Testing"; System.out.println("\nSubstring of 'This is Testing' from index 3: " + str8.substring(3)); System.out.println("Substring of 'This is Testing' from index 3 to 9: " + str8.substring(3,9)); //subsequence: this gives subsequence of string and it behaves exactly same as substring(beginIndex,endIndex) method System.out.println("Subsequence of 'This is Testing' from index 3 to 9: " + str8.subSequence(3,9)); //concat: this method combines string to specified string System.out.println("\nConcatenation: " + str8.concat(" Added at last")); /* replace: this method replaces each substring which matches first argument with second argument first argument and second argument could be char or CharSequence replaceFirst: replace: this method replaces first occurrence of substring which matches first argument with second argument replaceAll: this method replaces each substring which matches first argument with second argument */ System.out.println("\nReplacing 'T' with 'P' in 'This is Testing': " + str8.replace('T','P')); System.out.println("Replacing 'is' with 'was' in 'This is Testing': " + str8.replace("is","was")); System.out.println("Replacing first 'is' with 'was' in 'This is Testing': " + str8.replaceFirst("is","was")); System.out.println("Replacing each 'is' with 'was' in 'This is Testing': " + str8.replaceAll("is","was")); //matches: returns true if string matches the specified regular expression System.out.println("\n'This is Testing' matches 'This(.*)' regex pattern: " + str8.matches("This(.*)")); System.out.println("'This is Testing' matches '(.*)This' regex pattern: " + str8.matches("(.*)This")); /* split: splits string around matches of the specified regular expression and returns array of string it can also take int as second parameter that controls the number of times the pattern is applied and therefore affects the length of the resulting array. if second parameter is n then pattern comparison applied n - 1 times and the array's last entry will contain all input beyond the last matched delimiter */ String str9 = "This:is:test:are:you:ready"; System.out.println("\n" + str9 + " after splitting"); for(String s : str9.split(":")){ System.out.print(s + " "); } System.out.println("\n" + str9 + " after splitting with limit 4"); for(String s : str9.split(":",4)){ System.out.print(s + " "); } /* toLowerCase: converts all characters in the string to lower case toUpperCase: converts all characters in the string to upper case both method can take locale object as its argument to which it should be converted */ String upper = "TEST"; String lower = "test"; System.out.println("\n\nUpper to Lower: " + upper.toLowerCase()); System.out.println("Lower to Upper: " + lower.toUpperCase()); //trim: this method removes leading and trailing spaces from string String strwithspaces = " With Space "; System.out.println("\n'"+strwithspaces+"' after trimming: '" + strwithspaces.trim()+"'"); //toCharArray: this method converts string to character array String str10 = "ARRAY"; System.out.println("\nARRAY after converting to char array"); for(char c : str10.toCharArray()){ System.out.print("'"+c+"' "); } /* format: It is static method and returns a formatted string using the specified format string and arguments. it is similar to printf in 'C' programming language but does not print instead it gives formatted string it follows below syntax while formatting %[argument_index$][flags][width][.precision]conversion it can also take locale as its first argument */ java.util.Calendar c = java.util.Calendar.getInstance(); String s = String.format("Today is : %1$tm %1$te,%1$tY", c); String s2 = String.format("%1$.2f %.10f", 45.235485); System.out.println("\n\n" + s); System.out.println(s2); //valueOf: it is static method which converts specified parameter/value to string , parameter/value could be of any type float, double, int long, object, etc. String number1 = String.valueOf(50); String number2 = String.valueOf(5.9); System.out.println("Number 1: " + number1 + " Number 2: " + number2); /* This method returns a canonical representation for the string object. A pool of strings which is initially empty, is maintained privately by the String class. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the String.equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. */ String str11 = new String("Interned String"); System.out.println("\nInterned: " + str11.intern()); /* copyValueOf: this method returns string containing characters of specified character array it can also return string that contains the characters of the subarray of the specified character array, by taking offset and length of subarray */ char[] carr = new char[]{'C','H','A','R','A','C','T','E','R'}; System.out.println("\nCopied value from character array: " + String.copyValueOf(carr)); System.out.println("Copied subarray from character array: " + String.copyValueOf(carr,0,4)); }} Output Length of str is 0 Length of str2 is 4 Length of str3 is 9str is empty: true str2 is empty: false Character at index 2 in str2 is s ‘T’ ‘e’ ‘s’ ‘t’Comparing String reference: false Comparing String value: truecompstr1 and compstr3 are equal: true TEST and test are equal: false TEST and test are equal: true compareTo Test with Testing: -3 compareTo Testing with Test: 3 Matching region: true This is Testing starts with This: true This is Testing starts with this: true Index of ‘Test’ in ‘This is Testing’: 8 Index of ‘is’ in ‘This is Testing’: 2 Index of ‘is’ in ‘This is Testing’ after offset 3: 5 Last Index of ‘is’ in ‘This is Testing’: 5 Last Index of ‘is’ in ‘This is Testing’ before offset 4: 2 Substring of ‘This is Testing’ from index 3: s is Testing Substring of ‘This is Testing’ from index 3 to 9: s is T Subsequence of ‘This is Testing’ from index 3 to 9: s is T Concatenation: This is Testing Added at last Replacing ‘T’ with ‘P’ in ‘This is Testing’: Phis is Pesting Replacing ‘is’ with ‘was’ in ‘This is Testing’: Thwas was Testing Replacing first ‘is’ with ‘was’ in ‘This is Testing’: Thwas is Testing Replacing each ‘is’ with ‘was’ in ‘This is Testing’: Thwas was Testing ‘This is Testing’ matches ‘This(.*)’ regex pattern: true ‘This is Testing’ matches ‘(.*)This’ regex pattern: false This:is:test:are:you:ready after splitting This is test are you ready This:is:test:are:you:ready after splitting with limit 4 This is test are:you:ready Upper to Lower: test Lower to Upper: TEST ‘ With Space ‘ after trimming: ‘With Space’ ARRAY after converting to char array ‘A’ ‘R’ ‘R’ ‘A’ ‘Y’ Today is : 08 30,2015 45,24 45,2354850000 Number 1: 50 Number 2: 5.9 Interned: Interned String Copied value from character array: CHARACTER Copied subarray from character array: CHAR Thank for visiting Please share if you like it