Examples of the String object's immutability :
String s = "abc"; // The value of "s" is still "abc" and not "ABC" // And the value of "x" is "ABC" String x = s.toUpperCase(); System.out.print(s); // Output "abc" System.out.print(xs); // Output "ABC"
Eg.
String s = "abc"; // new value "abcdef" s += "def";
The String literal pool
In the previous example, JVM (Java Virtual Machine) created not one but three String objects in memory! At the first line, the variable 's' refers to the String object holding the value "abc". At the second line JVM created two String objects: one holding "def" and an other one holding "abcdef". The variable 's' refers then to the String object holding "abcdef".
Each time a string literal is declared, JVM checks the memory called "String literal pool" or ""String constant pool" to see if an identical String object already exists:
Eg.
// create a String object with // the value "abc" in the pool String s = "abc"; // the string "abc" exists already // in the "String constant pool", // therefore JVM does not create // a new String object and the // variable 'x' refers to // the same object than the variable 's'. String x = "abc";
Note that the "String constant pool" is only used for literal strings. The code String declared below will not be added to the pool or use it:
// because this is not a string literal,
// JVM creates a new string object in memory (non-pool)
String y = new String("abc");
Important methods of the String class:
Instance methods
|
Description
|
Example
In the examples below the variable "x" is defined as follow:
String x = "Example";
|
char charAt(int index)
|
Returns the character located at the specified index (zero based)
|
System.out.print(x.charAt(2)); // output 'a'
|
String concat(String s)
|
Appends one String to the end of another
|
System.out.print(x.concat(" java")); // output 'Example java', note that the value of the String object to which "x" refers has not changed, it is still "Example"
|
boolean equalsIgnoreCase(String s)
|
Determines the equality of two Strings, ignoring case
|
System.out.print(x.equalsIgnoreCase("EXAMPLE")); // output 'true'
|
int length()
|
Returns the number of characters in a String
|
System.out.print(x.length()); // output '7'
|
String replace(char old, char new)
|
Replaces occurrences of a character with a new character
|
System.out.print(x.replace('e', 'E')); // output 'ExamplE'
|
String substring(int begin)
String substring(int begin, int end)
|
Returns a part of a String
The parameter 'begin' starts with zero and the parameter 'end' starts with one.
|
System.out.print(x.substring(2, 6)); // output "ampl"
|
String toLowerCase()
|
Returns a String with upper-case characters converted
|
System.out.print(x.toLowerCase()); // output 'example'
|
String toUpperCase()
|
Returns a String with lowercase characters converted
|
System.out.print(x.toUpperCase()); // output 'EXAMPLE'
|
String toString()
|
Returns the value of a String
|
System.out.print(x.toString()); // output 'Example'
|
String trim()
|
Removes white spaces from the any part of a String
|
String x = " Exa mple ";
System.out.print(x.trim()); // output 'Example'
|
StringBuffer and StringBuilder
The classes "StringBuffer"and "StringBuilder"unlike "String"are mutable. It means that it is possible to modify their values. These two classes expose exactly the same API.
Note that "StringBuilder" has been introduced since Java version 5. Sun recommends its usage over "StringBuffer" as its methods are not synchronized for thread safety and it is much faster.
From Sun's API:
<< "StringBuilder" is designed for use as a drop-in replacement for "StringBuffer" in places where the string buffer was being used by a single thread (as it is generally the case). Where possible, it is recommended that this class be used in preference to "StringBuffer" as it will be faster under most implementations. >>
The usage of these classes over "String" may be extremely useful when it is come to manipulating important amount of strings while reading and/or writing from/to a file. You can save important quantity of memory by using these classes at the right place.
Examples of the StringBuilder or StringBuffer object's mutability :
StringBuilder s = new StringBuilder("String test");
// Unlike with the "String" object,
// the "StringBuilder" object's value has been
// set to "String test with Java" while the
// variable "s" is referring to the same object.
StringBuilder x =s.append(" with Java");
System.out.print(s); // Output "String test with Java"
System.out.print(x); // Output "String test with Java"
Example of "StringBuilder" usage with reading a file's contents:
// "StringBuilder" is faster
// than an immutable "String" object
StringBuilder fileContents = new StringBuilder();
try{
// We open a file
BufferedReader bufferedReader = new BufferedReader(new FileReader("/tmp/testFile.tmp"));
// We read the file line by line until the end of the file
// Note that "bufferedReader.readLine()" returns null
// if the end of the file has been reached.
String ligneToRead = null;
while( (ligneToRead = bufferedReader.readLine()) != null){
fileContents.append(ligneToRead);
}
// We close the stream
bufferedReader.close();
}catch(java.io.IOException ex) {
System.out.println("IOException while reading: "+ex.getMessage());
}
// We display the contents of the file
System.out.println("File's contents:");
System.out.println(fileContents);
Important methods of StringBuilder
Instance methods
|
Description
|
Example
In the examples below the variable "x" is defined as follow:
StringBuilder x = new StringBuilder("Example");
|
StringBuilder append(String s)
|
Update the value of the object
|
System.out.print(x.append(" Java")); // output "Example Java"
|
StringBuilder delete(int begin, int end)
|
Delete a portion of the string.
The parameter 'begin' starts with zero and the parameter 'end' starts with one.
|
System.out.print(x.delete(2, 5)); // output "Exle"
|
StringBuilder insert(int offset, String s)
|
Insert a string from the position given by the variable "offset" (start by zero).
|
System.out.print(x.insert(2, "---")); // output "Ex---ample"
|
StringBuilder reverse()
|
Reverse the positions of the characters in a string.
|
System.out.print(x.reverse()); // output "elpmaxE"
|
String toString()
|
Return a String object from the "StringBuilder" object.
|
System.out.print(s.toString); // output "Example"
|