The String Class
The String class defines the String object and the methods that can be applied to strings. The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Specifications for this class and methods are located on the web http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html.
Example:
String s = "abc";
String t = "def";
String f = "firetruck";
System.out.println ( s + t ) ; // prints abcdef to the screen
System.out.println ( f.substring ( 0, 4 ) ); // prints fire to the screen
System.out.println ( f.substring (4) ); // prints truck to the screen
Common String Methods:
Method | Result | Description |
charAt ( int i ) | char | Returns the character at position i of the string ( 0 based, ie. first character is position 0 ). |
compareTo ( String t ) | int | Compares one string to another based on unicode values. Returns an integer value that will be 0, if both strings are the same. |
concat ( String t ) | String | Adds (concatenates) two strings together. |
equals ( String t ) | boolean | Returns true when both strings are identical. |
equalsIgnoreCase ( String t ) | boolean | Returns true when both strings are the same (ignoring case differences) |
indexOf ( char c ) | int | Position of the first occurrence of character c in the string. |
indexOf ( String t ) | int | Position of the first occurrence of string t in the string being checked. |
length ( ) | int | Number of characters in the string. |
replace ( char c, char d) | String | Returns the equivalent string, but with each occurrence of c replaced with d. |
substring ( int i ) | String | Returns string starting at position i to the end of the string. |
substring ( int i, int j ) | String | Returns string starting at position i up to but not including position j. |
toLowerCase ( ) | String | Returns equivalent string in lower case. |
toUpperCase ( ) | String | Returns equivalent string in upper case. |
trim ( ) | String | Returns equivalent string with all leading and trailing white spaces removed. |