Creating Strings
Manipulating text is a common computer programming task. Several languages (perl, for instance) were purposely designed to include powerful text processing capabilities. Early Java versions were not designed with this in mind, so developers had to rely on third-party libraries to add decent string handling capabilities. But, with recent releases of the JDK, Java now has solid, built-in support for manipulating text through both regular expressions and enhanced string-related classes. In this tutorial, we'll take a look at Java's basic text processing class java.lang.String
String enjoys a special shortcut syntax for instantiating new String objects from string literals:
The text between double quotes is a string literal. By assigning a string literal to myName, you can avoid using the new keyword. In fact, this special shortcut syntax was designed to improve String performance: Each JVM only keeps one copy of each string literal. The following code creates a single string literal that both String references point to:
String literalOne = "I am a literal.";
//points to the same object as literalOne
String literalTwo = "I am a literal.";
But, you can still use new to create a String object:
String myName = new String("Arunkumar Subramaniam");
You can also instantiate an empty String object by passing in just a pair of empty double quotes:
String myName = "";
String myName = null;
char[] firstName = {'A', 'r', 'u', 'n' };
String myName = new String(firstName);
char[] name = myName.toCharArray();