|
We have already seen the string creation in chapter 9 when we discussed the equality operators. Here we will discuss it in brief for completing the discussion about strings.
1. The first way to create string object is by enclosing the characters in double quotes. The strings created in this way are called as string literals.
String str = "test"; // One String object & one reference variable is
// created
In this simple case, string literal “test” is created (on the literal pool) and the reference variable str will refer to it. String literals are also object, but they have specialty that they are not created if there is already a string literal with exactly same contents on the literal pool.
2. The second way is same as all Java objects are created, using the new keyword. For example,
String str = new String("test"); // Two string objects and one reference variable are created
In this case, two string objects are created. Since we used the new keyword, Java will create a new string object on memory heap and reference variable str will refer to it. However, before that a string literal “test” is created on the literal pool. In the example, we have seen we used a String constructor that takes another string as argument. The String class has several other overloaded constructors that take different arguments such as char array, byte array and a StringBuffer object to create a string object.