How to Declare and Initialize a String in Java:
There are two main ways to create Java Strings. One is by creating a String literal (see top line in picture below). The other is to explicitly create a new Object in memory (See second line below). I will avoid going into detail about how these differ as it involves discussing aliasing and how Java saves memory. Note: Unlike some other programming languages, in Java Strings must be enclosed in double quotes. Single quotes are used for chars, a primitive data type.
String str 1 = "Java Stuff";
String str2 = new String("Java Stuff");
Comparing Strings
You cannot compare
Strings (or any objects) with the == operator and get the results you probably expect -- two Strings that contain exactly the same characters will not necessarily be "==" to each other. To compare Strings to see if they contain the same (or similar) characters, you need to use certain String messages. Some of these include...equals
Use this message to see if one
String contains exactly the same characters, in the same order, as another. Send this message to one of the Strings, with the other as its parameter. This message returns a boolean result, True if the Strings contain the same characters, False if not. For example if ( command.equals( "quit" ) ) {
// This code will be executed if String command contains
// 'q', 'u', 'i', and finally 't' equalsIgnoreCase
This message is like
equals, except it ignores the capitalization of characters. For example if ( command.equalsIgnoreCase( "quit" ) ) {
// This code will be executed if String command contains
// "quit", "QUIT", "Quit", "qUiT", etc. compareTo
This message compares two
Strings to see which is alphabetically greater. Send this message to one of the Strings, with the other as its parameter. This message returns an integer, which is negative if the String to which you sent the message is less than the String provided as a parameter, positive if the String to which you sent the message is greater than the parameter, and 0 if the two Strings are equal. This comparison is case-sensitive, with lower-case letters considered to be greater than upper-case ones. For example if ( word.compareTo("dog") > 0 ) {
// This code will be executed if String word is
// alphabetically after "dog" compareToIgnoreCase
This message is like
compareTo, except that it compares Strings without regard to capitalization. For example, "A".compareToIgnoreCase( "a" ) returns 0, whereas
"A".compareTo( "a" ) returns a negative number (because upper-case "A" is considered less than lower-case "a").
Searching for Substrings
Many applications require you to know whether one
String contains another, without necessarily comparing the whole strings. For example, a silly book-censoring program might want to search the entire text of a book to see if it contains the words "sex", "drugs", or "rock-n-roll". One of the most helpful messages for searching Strings is...indexOf
This message returns the position in one
String where another String or character first appears. Send this message to the String in which you want to do the search. Positions are numbered from 0, i.e. the first character in a String is at position 0, the second at position 1, and so forth. This message returns -1 if it can't find the thing it is searching for. There are four variations on this message, depending on whether you are searching for a single character or a multi-character String, and whether you want to start the search at the beginning of the String or somewhere in the middle.indexOf( int c )- Searches for the first occurrence of character c (characters and ints are very similar in Java, so you can pass a
charparameter even 'though this message is formally declared as taking anint). indexOf( int c, int p )- Searches for the first occurrence of character c at or beyond position p.
indexOf( String s )- Searches for the first occurrence of
Strings. Returns the position of the first character of s, if any. indexOf( String s, int p )- Searches for the first occurrence of
Strings at or beyond position p.
Here are some examples of
indexOf in action: int pos = someString.indexOf( "rock-n-roll" );
// pos is now the position in someString of "rock-n-roll"
int pos2 = someString.indexOf( "rock-n-roll", pos );
// pos2 is the position of the 2nd occurrence of "rock-n-roll" in someString
String digits = "0123456789";
char c = ...;
if ( digits.indexOf(c) != -1 ) {
// Execute this code if character c is a digit Extracting Parts of a String
Another common operation on
Strings is picking substrings or characters out of them. Two messages are helpful for this:charAt
This message returns the single character at a particular position in a
String. The position of interest is the parameter to this message. For example, to make variable c equal to the fifth character from String someString, you could write (remember that characters are numbered starting at 0, so the fifth character really is at position 4): char c = someString.charAt( 4 ); substring
This message extracts a multi-character substring from a
String. There are two versions of this message, one with two integer parameters and the other with one. In the two-parameter version, the first parameter is the position of the first character to extract, and the second is the position one past the last character to extract. For example String source = "wombat";
String sub = source.substring( 1, 3 );
// String sub is now equal to "om" The one-parameter version extracts all characters from a designated position (the parameter) through the end of the
String. For example, with source defined as above... String tail = source.substring( 3 );
// String tail is now equal to "bat"