Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
A string is often created from a string literal--a series of characters enclosed in double quotes. For example, when it encounters the following string literal, the Java platform creates aString
object whose value isGobbledygook
.The"Gobbledygook"StringsDemo
program uses this technique to create the string referred to by thepalindrome
variable:You can also createString palindrome = "Dot saw I was Tod";String
objects as you would any other Java object: using thenew
keyword and a constructor. TheString
class provides several constructors that allow you to provide the initial value of the string, using different sources, such as an array of characters, an array of bytes, or a string buffer.Here's an example of creating a string from a character array:
The last line of this code snippet displays:char[] helloArray = { 'h', 'e', 'l', 'l', 'o' }; String helloString = new String(helloArray); System.out.println(helloString);hello
.You must always use
new
to create a string buffer. The StringsDemo program creates the string buffer referred to by dest, using the constructor that sets the buffer's capacity:This code creates the string buffer with an initial capacity equal to the length of the string referred to by the nameString palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuffer dest = new StringBuffer(len);palindrome
. This ensures only one memory allocation fordest
because it's just big enough to contain the characters that will be copied to it. By initializing the string buffer's capacity to a reasonable first guess, you minimize the number of times memory must be allocated for it. This makes your code more efficient because memory allocation is a relatively expensive operation.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.