Wednesday, 17 May 2017

Tutorial 11: StringBuilder Class and how to Format Strings


We have dealt with objects of type String in most of the past tutorials. We know that an object of type String holds textual data. Right?


Okay. So let us create a few objects of type String to remind ourselves about what we have previously learnt.


String name = “Brian”; //Assume Brian is the first name

name = name + “ ” + “Kennedy”; // Assume Kennedy is the second name

name = name + “ ” + “Bobby”; // Assume Bobby is the third name


Let us assume that the above are the three names of a single person.

If we print the value of name to the console, we like this:

System.out.println(name);

We would get Brian Kennedy Bobby as the output. Very straightforward right?

Figure 1: Using String concatenation to print out a name on the console.


Now, here is something you should know about String objects. Strings are immutable in Java, meaning that once created, you can never change it. So, whenever you add or make a modification to a String, a new String object is created and the previous one is not discarded. When you make another modification on the String object again, now you have three String objects.

In a small program, this may not be a big issue. But in a large program or a program in which many String objects are created, this becomes a major issue, because it means you risk the possibility of running out of memory.

So in the above example, when we wrote: String name = “Brian”; , a new String object was created. When we wrote name = name + “ ” + “Kennedy”; , a new String object was created. When we wrote name = name + “ ” + “Bobby”; ,  a new String was created. For programs with lots and lots of operations on String objects, this can become a major problem.

StringBuilder Class

And this brings us to the StringBuilder class. After noticing the inefficiencies of the String class in some contexts, such as the ones described above, Java designers created a StringBuilder class. Fundamentally, when you create an object of the type StringBuilder, you only have that one object created even if you make thousands of modifications to it. And this pretty much solves the problems associated with objects of type String.

Just like any other object in Java, we create an object of the StringBuilder class like this:

StringBuilder sb = new StringBuilder();

Now, you may or may not initialize the StringBuilder object by supplying a value in the constructor like this StringBuilder sb = new StringBuilder (“”);

To add text to the StringBuilder object, which we have labeled stringBuilder in this example, we can do the following:

            sb.append(“You are a person”);

      sb.append(“ and you live somewhere on earth”);

So in the above example, we are appending text to the StringBuilder object sb. When you append text to a StringBuilder object, you are not creating a new StringBuilder object. What we are doing is just modifying it. This is more efficient than using Strings, in which a new String is created every time the String object is modified. 

Now, what if you want to output the text in stored in the StringBuilder object to the console? You do this by calling the toString() function on the StringBuilder object like this:

            System.out.println(sb.toString());


Figure 2: Using the StringBuilder class. It is more efficient than String because there is only one instance while String objects are immutable.


As you can see, using a StringBuilder object is more efficient than using Strings. StringBuilder is more memory-efficient when it comes to appending text.


Since objects of the type StringBuilder return a StringBuilder object, you can do cool things with the append() method. You can chain many appends together like this:


StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append(“Hello there.”).append(“ How do you like my tutorials?”).append(“ I will be creating many of these soon!”);
Now, to get the string in the StringBuilder object stringBuilder, I will use the toString() method like this: stringBuilder.toString();


Figure 3: Chaining using the append() method in the StringBuilder class.

Advanced String Formatting


If I write this code, it will produce the following output:

System.out.println(“I am a string and \t I’ve moved one tab further \n now I’m in a newline”);




Figure 4: A program showing the use of the newline and tab characters.
\t tells Java to insert a tab.
\n tells Java to insert a new line.

Now, in the past tutorials, you noticed that when I write the following code, the words “Brian” and “Kennedy” appear on different lines:

System.out.println(“Brian”);
System.out.println(“Kennedy”);


Figure 5: A program showing that println outputs on different lines.


But what if I want the names to appear on the same line, despite the fact that I am writing them in different lines? To do this I will write:


System.out.print(“Brian”);
System.out.print(“Kennedy”);


Figure 6: A program showing that print outputs on the same line.


So, by just writing print instead of println, I can output the text in one line.

I can also use printf, if I want to have more control over the output. For example, if I write:


System.out.printf(“My name is %s I am %d years old and my ID number is %d”, “Brian”, 25, 11111111);

I will get the following output:



Figure 7: A program demonstrating how to use printf and the special formatting characters.

%s stands for strings.
%d stands for integers.
%f stands for doubles or floats.

Java will notice the special formatting characters %s, %d and % after the final quotation mark and fill these automatically as shown in the above program.
Now, between the % and the d or the % and the s or between the % and the f, you can place a number like this %10d or %10s or %4s. What this does is it outputs the integer value after ten character spaces, the string value after ten character spaces and the string value after four character spaces. As shown below:



Figure 8: A program demonstrating the functionality of printf and the special formatting characters, in this case, spacing out the output.

If you would like, you can left-align the values by placing a negative sign here: %-10d, %-10s, %-10s. What this does is it left-aligns the values and then prints whatever next value after 10 characters or whichever value is specified between the % and the d or the % and the s as shown below:

Figure 9: A program showing how to left-align your output by adding a negative sign before the integer that specifies the number of spacing characters.


The advantage of using printf and the special formatting characters is that it helps your output to appear neat. Everything lines up as you can see in the figure above. Remember that you should have as many arguments as you have special formatting characters.

Now, Java gives more control over double and floating values, whose special formatting character is %f. So when I write this System.out.printf(“The price is: %f”, 3.26589); Java will give the following output:


Figure 10: A program demonstrating the use of printf with floating point numbers.

If I want the floating point number to be output in two decimal places, I can write %.2f. The .2 tells Java that I want the floating point number to be output in two decimal points. So if you want three decimal places, you will write %.3f and if you want four decimal places you will write %.4f as shown below. If your initial floating point value had several decimal places, Java will round off your value. For example, if your value was 3.26589 and then you say %.2f, Java will output 3.27.


Figure 11: A program demonstrating that you can tell Java the number of decimal places to output using printf.

Now, you can combine the number of decimal places you want with the number of characters you want the floating point number to appear after. For example, if I write %10.3f, Java will output the value after ten character spaces because of the number 10.

Figure 12: A program demonstrating how to use printf to specify the number of decimal places to output and the number of character spacing.

Also, it will output the number as a three decimal place number because of the .3. If you want to left-align your number, you can write %-10.3f. The results are as shown in the figure below.

Figure 13: A program demonstrating how to use printf to specify the number of decimal places to output, left-alignment and the number of character spacing.


In the next tutorial, we are going to look at inheritance in Java, its meaning and why it is important to understand. This tutorial is important because it lays the foundation for the tutorial on polymorphism and inheritance.

If you have any questions or comments, please drop them in the comments section and I will answer or respond to them.

Until next time, stay safe.

No comments:

Post a Comment