Strings and StringBuffers
In Java, a string is an object (of class type String). There is
also a StringBuffer class that can be used for building and
manipulating string data.
- the String class - used to create and store immutable strings
(i.e. cannot be changed)
- the StringBuffer class - objects of this type are strings
that can be modified
The String class
- Part of java.lang package
- 13 constructors and close to 50 methods
-
String class API from java.sun.com -- full listing of
String class features
- Once you build a String object, it is fixed -- it cannot be
changed.
- This is easier than it sounds. The only methods that can alter or set
the instance variables are the constructors. All other methods that seem
to change a string do so by returning a brand new String
object
- You can assign a String reference variable to a new string,
discarding the old one
A common way to construct a String
One constructor allows the use of a string literal as the parameter.
Example string constructions:
String greeting = new String("Hello, World!");
String name = new String("Marvin Dipwart");
String subject = new String("Math");
// also, a shorthand notation for building strings (below)
String sentence = "The quick brown fox sat around for a while";
Some commonly used String class methods
- equals() -- for comparing two strings, returns true or
false
if (str1.equals(str2))
System.out.print("The strings are the same");
- compareTo() -- also for comparing two strings, good for
sorting.
if (str1.compareTo(str2) < 0)
System.out.print("str1 comes before str2 in lexicographic ordering");
else if (str1.compareTo(str2) == 0)
System.out.print("str1 is the same as str2");
else if (str1.compareTo(str2) > 0)
System.out.print("str2 comes before str1 in lexicographic ordering");
- equalsIgnoreCase() - just like equals(), except that
the case of the letters doesn't matter in making a match. For instance,
"Apple" would be equal to "apple" with this method.
- Note: Don't try to compare strings by using ==, <, >,
etc. These would only compare the String reference variables, not the
String objects themselves.
- Other comparison methods include regionMatches,
startsWith, and endsWith. See String class API for
full details
- concat() -- String concatenation. Returns a concatenation of
two strings.
String s1 = "Dog";
String s2 = "food";
String s3 = s1.concat(s2); // s3 now stores the string "Dogfood"
// note: s1 and s2 are NOT changed
- The + symbol also performs String concatenation (as we've already used
in print statements).
String s1 = "Cat";
String s2 = "nap";
String s3 = s1 + s2; // s3 now stores "Catnap" (s1 and s2 unchanged)
- substring() -- extracts part of a string and returns it.
Takes in two parameters (begin index and end index) or 1 parameter (begin
index). First character in a String has index 0. Substring returned is the
index range [begin,end)
String s1 = "Hello, World";
String s2 = s1.substring(0,5); // s2 is now "Hello".
// picks up indices 0 - 4
String s3 = s1.substring(0,7) + "Dolly";
System.out.print(s3); // prints "Hello, Dolly"
System.out.print(s3.substring(4)); // prints "o, Dolly"
// can even use substring on string literals
String s4 = "What's up doc?".substring(10,13); // s4 = "doc"
- length() -- returns a string's length (number of characters)
String s1 = "Hello";
String s2 = "Goodbye world";
System.out.print(s1.length()); // output: 5
System.out.print(s2.length()); // output: 13
- charAt() -- returns a specific character, given an index
String s1 = "Rumplestiltskin";
System.out.print(s1.charAt(0)); // output: R
System.out.print(s1.charAt(5)); // output: e
System.out.print(s1.charAt(12)); // output: k
- Some conversion methods
- toLowerCase() -- returns all lower case version of string
- toUpperCase() -- returns all upper case version of string
- trim() -- returns a string that eliminates leading and
trailing blank characters from original
- replace() -- returns a string with an old character
replaced with a new one. old character and new character passed as
parameters
String s1 = "Zebra";
String s2 = s1.toLowerCase(); // s2 is "zebra"
String s3 = s1.toUpperCase(); // s3 is "ZEBRA"
String s4 = " Apple ";
String s5 = s4.trim(); // s5 is "Apple"
String s6 = s5.replace('e', 'y'); // s6 is "Apply"
- valueOf() -- there are several of these methods. They are
static methods, and are used for converting other values to String
objects
int x = 12345;
String s7 = String.valueOf(4.56); // s7 is "4.56"
String s8 = String.valueOf(16); // s8 is "16"
String s9 = String.valueOf(x); // s9 is "12345"
The StringBuffer class
Creating
Three of the four constructors shown here. Here are sample creations:
// creates an empty string buffer with initial capacity of 16 characters
StringBuffer buf1 = new StringBuffer();
// creates empty string buffer with initial capacity given in parameter
StringBuffer buf2 = new StringBuffer(50);
// creates string buffer filled with argument -- initial capacity is
// length of given string plus 16
StringBuffer buf3 = new StringBuffer("Hello, World");
Some common StringBuffer methods
- append() -- adds data to string in the buffer, at the end.
Several versions for different parameter types (see API for full set)
StringBuffer buf1 = new StringBuffer();
buf1.append("Hello");
buf1.append(',');
buf1.append(" world!"); // buf1 is now "Hello, world!"
buf1.append(' ');
buf1.append(123.45); // buf1 is now "Hello, world! 123.45"
- insert() -- insert data at a certain starting index. Like
append, multiple versions for different types of data (see API
for full set)
StringBuffer buf2 = new StringBuffer();
buf2.append("Welcome home"); // buf2 now "Welcome home"
buf2.insert(8,"to my humble "); // buf2 = "Welcome to my humble home"
- delete() -- delete data from a string buffer
StringBuffer buf3 = new StringBuffer("abcdefghijklm");
buf3.delete(4,9); // deletes indices 4-8. buf3 is now "abcdjklm"
- deleteCharAt() -- delete a character at specified index
StringBuffer buf4 = new StringBuffer("abcdefg");
buf4.deleteCharAt(3); // buf4 is now "abcefg"
buf4.deleteCharAt(1); // buf4 is now "acefg"
- reverse() -- reverses the contents of the string buffer
- setCharAt -- sets a character at specified index (similar to
deleteCharAt
- capacity() -- returns current capacity of buffer
- length() -- returns length of current string in buffer (less
than or equal to capacity)
- setLength() -- sets the exact length of the string in the
buffer to new value (parameter). This is the actual string, not the
capacity. If the new length is smaller than previous length, characters
are truncated from the string. If new length bigger, null characters are
appended.
- charAt() -- returns character at a specified index
(parameter)
Command line arguments
Recall that the main method of a Java program looks like this:
public static void main(String[] args)
The String[] args part allows a set of arguments to be passed
into the program from the command line. Suppose we execute a java program
with the following command:
java MyProgram file1.txt output lazy
Inside the main program, the arguments are stored in an array of strings:
args[0] is "file1.txt"
args[1] is "output"
args[2] is "lazy"
args.length -- stores the number of parameters passed (3, in this example)