- Because Strings are objects, you can create a
String
object by using the keyword new
and a String
constructor method, just as you would create any other object.
String name = new String();
String name2 = new String(“Nancy”);
- 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 Strings
have a shortcut like this. All other objects are constructed by using the new
operator.
Many new Java programmers get confused because of this shortcut and believe that Strings
are primitive data types. However, Strings
are objects and therefore have behaviors and attributes.