| |
String Constructors | page 4 of 12 |
You create a String object by using the keyword new and the String constructor method, just as you would create an object of any other type.
Constructor | Sample syntax |
String();
|
// emptyString is a reference to an empty string
String emptyString = new String();
|
String(String value);
|
String aGreeting;
// aGreeting is reference to a Stringa
Greeting = new String("Hello world");
// Shortcut for constructing String objects
aGreeting = "Hello world";
// anotherGreeting is a copy of aGreetingString
anotherGreeting = new String(aGreeting);
|
Though they are not primitive types, strings are so important and frequently used that Java provides additional syntax for declaration:
String aGreeting = "Hello world";
A String created in this short-cut way is called a String literal. Only String s have a short-cut like this. All other objects are constructed by using the new operator.
|