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, a string buffer, or a string builder. The following table shows the constructors provided by the String class.
* The
Constructors in the String
Class*Constructor Description String(byte[])
String(byte[], int, int)
String(byte[], int, int, String)
String(byte[], String)Creates a string whose value is set from the contents of an array of bytes. The two integer arguments, when present, set the offset and the length, respectively, of the subarray from which to take the initial values. The String argument, when present, specifies the character encoding to use to convert bytes to characters. String(char[])
String(char[], int, int)Creates a string whose value is set from the contents of an array of characters. The two integer arguments, when present, set the offset and the length, respectively, of the subarray from which to take the initial values. String
class defines other constructors not listed in this table. Those constructors have been deprecated, and/or their use is not recommended.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 or string builder. Because the two classes have similar constructors, the following table lists only the constructors for string builders.
Constructors in the StringBuilder
ClassConstructor Description StringBuilder() Creates an empty string builder. StringBuilder(CharSequence) Constructs a string builder containing the same characters as the specified CharSequence
.StringBuilder(int) Creates an empty string builder with the specified initial capacity. StringBuilder(String) Creates a string builder whose value is initialized by the specified string.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.