Java Strings Quick Reference
Java Strings Quick Reference
Creating a String: String s = new String ( "Hello World"); or String s = "Hello World"; Java String Methods ( all methods listed are public ) These methods use zero-based indexing
Strings in Java are immutable ( cannot be changed ). "Changing" a String causes a new String object to be created.
Requires an integer argument which indicates the position within the String of the character to be returned. ( start counting at 0 ). pos is in the range 0 to length of the String 1.
s1.charAt(3)
int compareTo(String s)
Returns: Zero if the strings are the same Negative number if the calling object is less than the argument object Positive number if the calling object is greater than the argument object
s1.endsWith("world")
Evaluate contents of two Strings to determine if they are equivalent.
s1.equals("Hello")
s1.indexOf('e')
Returns the length of the String ( start counting at 1 )
s1.length( )
s = "abc";
s.length() --> 3
Splits this string around matches of the given regular expression. Similar to use of StringTokenizer object. Returns an array of Strings (tokens).
String sentence, words[]; sentence = input.nextLine(); words = sentence.split(" "); //" " is the reg. exp.
Takes a String argument and returns true or false if a String object does or does not begin with the specified argument.
boolean startsWith(String s) String substring(int n, int m) String toLowerCase( ) String toUpperCase( ) String [ static method ] toString( <type> x) String trim( )
s1.startsWith("world")
Extracts a substring of a String begining at element n and ending at element m-1
s1.substring(n, m)
s1.toLowerCase( )
s1.toUpperCase( )
String.toString(x)
Returns a copy of the string, with leading and trailing whitespace omitted.
s1.trim()