<< Chapter < Page | Chapter >> Page > |
The first thing to notice is that a String object can be created using either of the following constructs:
String str1 = new String("String named str2");String str2 = "String named str1";
The first approach uses the new operator to instantiate an object while the shorter version doesn't use the new operator.
Later I will discuss the fact that
The next thing to notice is that a similar alternative strategy does not hold for the StringBuffer class.
For example, it is not possible to create a StringBuffer object without use of the new operator. (It is possible to create a reference to a StringBuffer object but it is later necessary to use the new operator to actually instantiate an object.)
Note the following code fragments that illustrate allowable and non-allowable instantiation scenarios for StringBuffer objects.
//allowed
StringBuffer str3 = new StringBuffer("StringBuffer named str3");
//not allowed//StringBuffer str4 = "StringBuffer named str4";
o.d("Try to create and append to StringBuffer " +"without using new -- not allowed");
//StringBuffer str7;//str7.append("StringBuffer named str7");
To review what you learned in an earlier module, three steps are normally involved in creating an object (but the third step may be omitted) .
The following code fragment performs all three steps:
StringBuffer str3 =
new StringBuffer("StringBuffer named str3");
The code
StringBuffer str3
declares the type and name of a reference variable of the correct type for the benefit of the compiler.
The new operator allocates memory for the new object.
The constructor call
StringBuffer("StringBuffer named str3")
constructs and initializes the object.
The instantiation of the StringBuffer object shown above uses a version of the constructor that accepts a String object and initializes the StringBuffer object when it is created.
The following code fragment instantiates an empty StringBuffer object of a default capacity and then uses a version of the append method to put some data into the object. (Note that the data is actually a String object -- a sequence of characters surrounded by quotation marks.)
//default initial length
StringBuffer str5 = new StringBuffer();//modify length as needed
str5.append("StringBuffer named str5");
It is also possible to specify the capacity when you instantiate a StringBuffer object.
Some authors suggest that if you know the final length of such an object, it is more efficient to specify that length when the object is instantiated than tostart with the default length and then require the system to increase the length "on the fly" as you manipulate the object.
Notification Switch
Would you like to follow the 'Object-oriented programming (oop) with java' conversation and receive update notifications?