Working with String Class
The String class provides methods for manipulating individual characters of the string, comparing strings, extracting substrings, searching strings, and for converting a string to uppercase or to lowercase.
Some of the frequently used methods of String class are as follows:
The length() method is used to find the length of a string. For example,
System.out.println(str.length()); //output: 5
The charAt() method is used to retrieve the character value at a specific index. The index ranges from zero to length() -1. The index of the first character starts at zero. For example,
System.out.println(str.charAt(2)); //output: ‘1’
The concat() method is used to concatenate a string specified as argument to the end of another string. If the length of the string is zero, the original String object is returned, otherwise a new String object is returned.
System.out.println(str.concat(“World”)); //output: ‘HelloWorld’
The compareTo() method is used to compare two String objects. The comparison returns an integer value as the result. The comparison is based on the Unicode value of each character in the strings. That’s is, the result will return a negative value, if the argument string is alphabetically greater than the original string. The result will return a positive value, if argument string alphabetically lesser than the original string and the result will return a value of zero, if both the strings are equal.
System.out.println(str. compareTo(“World”)); /output: -15
The output is 15 because, the second string “world” begins with ‘W’ which is alphabetically greater than the first character ‘H’ of the original string, str. The difference between the position of ‘H’ and ‘W’ is 15. Since, ‘H’ is smaller than ‘W’, the result will be -15.
Note: Unicode is a standard that provides a unique number for every character irrespective of the platform, program, or language. The Unicode standard has been adopted for programming by major industry leaders such as IBM, Apple, Microsoft, HP, Oracle, Sun, SAP, and several others.
The indexOf() method returns the in dex of the first occurrence of the specified character or string within a string.
If the character or string is not found, the method returns -1. For example,
System.out.println(str.indexOf(“e”)); /output: 1
The lastIndexOf() method returns the index of the last occurrence of a specified character of string from within a string. The specified character of string is searched backwards that is the search begins from the last character. For example.
System.out.println(str.lastIndexOf(“1”)); //output: 3
The toString() method is used to return a String object. It is used to convert values of other data types into string. For example,
The trim() method returns a new string by trimming the leading and trailing whitespace from the current string. For example,
String str1= “ Hello ”;
System.out.println(str1.trim()); //output: ‘Hello’
The trim() method will return ‘Hello’ after removing the spaces.