Caution |
Confusing length() with length leads to compiler errors. length() is a method that returns the current number of characters in a String's value array, whereas length is a read-only array field that returns the maximum number of elements in an array. |
- public String substring(int beginIndex, int endIndex) creates a new String that contains every character in the string beginning at beginIndex and ending at one position less than endIndex, and returns that object's reference. However, if beginIndex contains 0 and endIndex contains the string's length, this method returns a reference to the current String. Furthermore, if beginIndex is negative, endIndex is greater than the string's length, or beginIndex is greater than endIndex, this method throws an IndexOutOfBoundsException object. Example: System.out.println ("Test string.".substring (5, 11)); (output: string).
- public char [] toCharArray() creates a new character array, copies the contents of the current String's value array to the new character array, and returns the new array's reference. Example: String s = new String ("account"); char [] ch = s.toCharArray ();.
- public String trim() completes one of two tasks:
- Creates a new String with the same contents as the current String—except for leading and trailing white space characters (that is, characters with Unicode values less than or equal to 32)—and returns that reference
- Returns the current String's reference if no leading/trailing white space characters exist
Example: System.out.println ("[" + " \tabcd ".trim () + "]");(output: [abcd]).
public static string valueOf(int i) creates a new String containing the character representation of i's integer value and returns that object's reference. Example: String s = String.valueOf (20); s += " dollars"; System.out.println (s); (output: 20 dollars).
No comments:
Post a Comment