Skip to content Skip to navigation

OpenStax-CNX

You are here: Home » Content » Jb0280: Java OOP: String and StringBuffer

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Jb0280: Java OOP: String and StringBuffer

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: This module discusses the String and StringBuffer classes in detail.

Preface

This module discusses the String and StringBuffer classes in detail.

Viewing tip

I recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the listings while you are reading about them.

Listings

Introduction

A string in Java is an object. Java provides two different string classes from which objects that encapsulate string data can be instantiated:

  • String
  • StringBuffer

The String class is used for strings that are not allowed to change once an object has been instantiated (an immutable object) . The StringBuffer class is used for strings that may be modified by the program.

You can't modify a String object, but you can replace it

While the contents of a String object cannot be modified, a reference to a String object can be caused to point to a different String object as illustrated in the sample program shown in Listing 1 . Sometimes this makes it appear that the original String object is being modified.

1
Listing 1: File String01.java.

/*File String01.java Copyright 1997, R.G.Baldwin
This application illustrates the fact that while a String 
object cannot be modified, the reference variable can be 
modified to point to a new String object which can have 
the appearance of modifying the original String object.

The program was tested using JDK 1.1.3 under Win95.

The output from this program is

Display original string values
THIS STRING IS NAMED str1
This string is named str2
Replace str1 with another string
Display new string named str1
THIS STRING IS NAMED str1 This string is named str2
Terminating program

**********************************************************/

class String01{
  String str1 = "THIS STRING IS NAMED str1";
  String str2 = "This string is named str2";
  
  public static void main(String[] args){
    String01 thisObj = new String01();
    System.out.println("Display original string values");
    System.out.println(thisObj.str1);
    System.out.println(thisObj.str2);
    System.out.println("Replace str1 with another string");
    thisObj.str1 = thisObj.str1 + " " + thisObj.str2;
    System.out.println("Display new string named str1");
    System.out.println(thisObj.str1);
    System.out.println("Terminating program");
  }//end main()
}//end class String01

It is important to note that the following statement does not modify the original object pointed to by the reference variable named str1 .

Note:


thisObj.str1 = thisObj.str1 + " " + thisObj.str2;

Rather, this statement creates a new object, which is concatenation of two existing objects and causes the reference variable named str1 to point to the new object instead of the original object.

The original object then becomes eligible for garbage collection (unless there is another reference to the object hanging around somewhere) .

Many aspects of string manipulation can be accomplished in this manner, particularly when the methods of the String class are brought into play.

Why are there two string classes?

According to The Java Tutorial by Campione and Walrath:

Note:

"Because they are constants, Strings are typically cheaper than StringBuffers and they can be shared. So it's important to use Strings when they're appropriate."

Creating String and StringBuffer objects

The String and StringBuffer classes have numerous overloaded constructors and many different methods. I will attempt to provide a sampling of constructors and methods that will prepare you to explore other constructors and methods on your own.

The next sample program touches on some of the possibilities provided by the wealth of constructors and methods in the String and StringBuffer classes.

At this point, I will refer you to Java OOP: Java Documentation where you will find a link to online Java documentation. Among other things, the online documentation provides a list of the overloaded constructors and methods for the String and StringBuffer classes.

As of Java version 7, there are four overloaded constructors in the StringBuffer class and about thirteen different overloaded versions of the append method. There are many additional methods in the StringBuffer class including about twelve overloaded versions of the insert method.

As you can see, there are lots of constructors and lots of methods from which to choose. One of your challenges as a Java programmer will be to find the right methods of the right classes to accomplish what you want your program to accomplish.

The sample program named String02

The sample program shown in Listing 2 illustrates a variety of ways to create and initialize String and StringBuffer objects.

2
Listing 2: File String02.java.

/*File String02.java Copyright 1997, R.G.Baldwin
Illustrates different ways to create String objects and 
StringBuffer objects.

The program was tested using JDK 1.1.3 under Win95.

The output from this program is as follows.  In some cases,
manual line breaks were inserted to make the material fin
this presentation format.

Create a String the long way and display it
String named str2

Create a String the short way and display it
String named str1

Create, initialize, and display a StringBuffer using new
StringBuffer named str3

Try to create/initialize StringBuffer without 
using new - not allowed

Create an empty StringBuffer of default length
Now put some data in it and display it
StringBuffer named str5

Create an empty StringBuffer and specify length 
when it is created
Now put some data in it and display it
StringBuffer named str6

Try to create and append to StringBuffer without 
using new -- not allowed

**********************************************************/

class String02{
  void d(String displayString){//method to display strings
    System.out.println(displayString);
  }//end method d()

  public static void main(String[] args){
    String02 o = new String02();//obj of controlling class
    
    o.d("Create a String the long way and display it");
    String str1 = new String("String named str2");
    o.d(str1 + "\n");
    
    o.d("Create a String the short way and display it");
    String str2 = "String named str1";
    o.d(str2 + "\n");
  
    o.d("Create, initialize, and display a StringBuffer " +
                                              "using new");
    StringBuffer str3 = new StringBuffer(
                                "StringBuffer named str3");
    o.d(str3.toString()+"\n");

    o.d("Try to create/initialize StringBuffer without " +
                              "using new - not allowed\n");
    //StringBuffer str4 = "StringBuffer named str4";x    
    
    o.d("Create an empty StringBuffer of default length");
    StringBuffer str5 = new StringBuffer();
    
    o.d("Now put some data in it and display it");
    //modify length as needed
    str5.append("StringBuffer named str5");
    o.d(str5.toString() + "\n");
    
    o.d("Create an empty StringBuffer and specify " +
                             "length when it is created");
    StringBuffer str6 = new StringBuffer(
                      "StringBuffer named str6".length());
    o.d("Now put some data in it and display it");    
    str6.append("StringBuffer named str6");
    o.d(str6.toString() + "\n");
    
    o.d("Try to create and append to StringBuffer " +
                      "without using new -- not allowed");
    //StringBuffer str7;
    //str7.append("StringBuffer named str7");
  }//end main()  
}//end class String02

Alternative String instantiation constructs

The first thing to notice is that a String object can be created using either of the following constructs:

Note:

Alternative String instantiation 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 second approach is not simply a shorthand version of the first construct, but that
  • they involve two different compilation scenarios with the second construct being more efficient than the first.

Instantiating StringBuffer objects

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.

Note:

Instantiating 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");

Declaration, memory allocation, and initialization

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) .

  • declaration
  • memory allocation
  • initialization

The following code fragment performs all three steps:

Note:

Declaration, memory allocation, and initialization

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.

Instantiating an empty StringBuffer 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.)

Note:

Instantiating an empty StringBuffer object

//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 to start with the default length and then require the system to increase the length "on the fly" as you manipulate the object.

This is illustrated in the following code fragment. This fragment also illustrates the use of the length method of the String class just to make things interesting. (A simple integer value for the capacity of the StringBuffer object would have worked just as well.)

Note:

Instantiating a StringBuffer object of a non-default length

    StringBuffer str6 = new StringBuffer(
                "StringBuffer named str6".length());
    str6.append("StringBuffer named str6");

Accessor methods

The following quotation is taken directly from The Java Tutorial by Campione and Walrath.

Note:

"An object's instance variables are encapsulated within the object, hidden inside, safe from inspection or manipulation by other objects. With certain well-defined exceptions, the object's methods are the only means by which other objects can inspect or alter an object's instance variables. Encapsulation of an object's data protects the object from corruption by other objects and conceals an object's implementation details from outsiders. This encapsulation of data behind an object's methods is one of the cornerstones of object-oriented programming."

The above statement lays out an important consideration in good object-oriented programming.

The methods used to obtain information about an object are often referred to as accessor methods .

Constructors and methods of the String class

I told you in an earlier section that the StringBuffer class provides a large number of overloaded constructors and methods. The same holds true for the String class.

Once again, I will refer you to Java OOP: Java Documentation where you will find a link to online Java documentation. Among other things, the documentation provides a list of the overloaded constructors and methods for the String class

String objects encapsulate data

The characters in a String object are not directly available to other objects. However, as you can see from the documentation, there are a large number of methods that can be used to access and manipulate those characters. For example, in an earlier sample program ( Listing 2 ) , I used the length method to access the number of characters stored in a String object as shown in the following code fragment.

Note:


StringBuffer str6 = new StringBuffer(
                    "StringBuffer named str6".length());

In this case, I applied the length method to a literal string, but it can be applied to any valid representation of an object of type String .

I then passed the value returned by the length method to the constructor for a StringBuffer object.

As you can determine by examining the argument lists for the various methods of the String class,

  • some methods return data stored in the string while
  • other methods return information about that data.

For example, the length method returns information about the data stored in the String object.

Methods such as charAt and substring return portions of the actual data.

Methods such toUpperCase can be thought of as returning the data, but returning it in a different format.

Creating String objects without calling the constructor

Methods in other classes and objects may create String objects without an explicit call to the constructor by the programmer. For example the toString method of the Float class receives a float value as an incoming parameter and returns a reference to a String object that represents the float argument.

Memory management by the StringBuffer class

If the additional characters cause the size of the StringBuffer to grow beyond its current capacity when characters are added, additional memory is automatically allocated.

However, memory allocation is a relatively expensive operation and you can make your code more efficient by initializing StringBuffer capacity to a reasonable first guess. This will minimize the number of times memory must be allocated for it.

When using the insert methods of the StringBuffer class, you specify the index before which you want the data inserted.

The toString method

Frequently you will need to convert an object to a String object because you need to pass it to a method that accepts only String values (or perhaps for some other reason) .

All classes inherit the toString method from the Object class. Many of the classes override this method to provide an implementation that is meaningful for objects of that class.

In addition, you may sometimes need to override the toString method for classes that you define to provide a meaningful toString behavior for objects of that class.

I explain the concept of overriding the toString method in detail in the module titled Java OOP: Polymorphism and the Object Class .

Strings and the Java compiler

In Java, you specify literal strings between double quotes as in:

Note:

Literal strings

"I am a literal string of the String type."

You can use literal strings anywhere you would use a String object.

You can also apply String methods directly to a literal string as in an earlier program that calls the length method on a literal string as shown below.

Note:

Using String methods with literal strings

StringBuffer str6 = new StringBuffer(
	       StringBuffer named str6".length());

Because the compiler automatically creates a new String object for every literal string, you can use a literal string to initialize a String object (without use of the new operator) as in the following code fragment from a previous program :

Note:


String str1 = "THIS STRING IS NAMED str1";

The above construct is equivalent to, but more efficient than the following, which, according to The Java Tutorial by Campione and Walrath, ends up creating two String objects instead of one:

Note:


String str1 = new String("THIS STRING IS NAMED str1");

In this case, the compiler creates the first String object when it encounters the literal string, and the second one when it encounters new String() .

Concatenation and the + operator

The plus (+) operator is overloaded so that in addition to performing the normal arithmetic operations, it can also be used to concatenate strings.

This will come as no surprise to you because we have been using code such as the following since the beginning of this group of Programming Fundamentals modules:

Note:


String cat = "cat"; 

System.out.println("con" + cat + "enation");

According to Campione and Walrath, Java uses StringBuffer objects behind the scenes to implement concatenation. They indicate that the above code fragment compiles to:

Note:


String cat = "cat"; 
System.out.println(new StringBuffer().append("con").
                      append(cat).append("enation"));

Fortunately, that takes place behind the scenes and we don't have to deal directly with the syntax.

Run the programs

I encourage you to copy the code from Listing 1 and Listing 2 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Looking ahead

As you approach the end of this group of Programming Fundamentals modules, you should be preparing yourself for the more challenging ITSE 2321 OOP tracks identified below:

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Jb0280: Java OOP: String and StringBuffer
  • File: Jb0280.htm
  • Originally published: 1997
  • Published at cnx.org: 11/25/12
  • Revised: 01/02/13

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

-end-

Content actions

Download module as:

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks