Java: String Builder

Just when you thought we were done with strings, there is (unfortunately) one more area to cover.

Using string concatenation is pretty common in coding, but in Java doing things like that leads to lots of new objects being created, which wastes resources. Fortunately, there’s a tool you can use to work around that problem. What is it? Well, I’m not going to insult my or your intelligence by stating it.

Using String Builder

(Damn it!) The String Builder is a utility provided by Java that lets you easily build strings, without having to worry about constantly creating new objects. Its usage is below.

StringBuilder builder = new StringBuilder(); //create the string builder object
for(char current = 'a'; current <= 'z'; current++){
  alpha.append(current);
}
System.out.println(alpha);

Pretty simple, right? Calling the append function and passing in a string adds that string to the string builder. Calling the toString function will return a string with the value of all things appended to the string builder object. Something to note is that calling append on the string builder returns a reference to the string builder object itself. Don’t forget, no new object is created when calling append.

A StringBuilder can be made in a few different ways, as below.

StringBuilder builder1= new StringBuilder();
StringBuilder builder2 = new StringBuilder("builder");
StringBuilder builder3 = new StringBuilder(5);

The first way we showcased above, line 2 sets the current value of the string builder to “animal”, which can be appended to as normal. Line 3 sets the capacity of the builder. That said, if you append something longer than 10 characters to the builder, it will just increase the capacity as normal. It should be noted to not fall into making the mistake below.

StringBuilder builder = new StringBuilder();
builder.append("Some" + "text");

In this example, “Some” is concatenated to “text”, making a new object, before append is called, which sort of defeats the purpose.

That’s the basics of the StringBuilder object. It’s outside the scope of this article, but I recommend ctrl-clicking on the append function in your IDE of choice (insert sarcastic comment about why IDE X is clearly superior to IDE Y here), to see how the code to add strings to the builder is handled, it’s pretty interesting, and isn’t even implemented using the Java language!

 

StringBuilder Functions

There are a couple of other functions available for the string builder, but they function pretty much the same as those functions do on a string object.

charAt, indexOf, length, and substring all work similar to how they are implemented on the string object. As you know by now, though, string builders can modify their value, so as well as appending text, we can also modify what is already there, as shown by these following functions that exist on the builder.

insert(int offset, String str)
This will insert the string to the passed in index. It will move the existing string data in the builder to accommodate this. Similar to string functions, if you set an index that is larger than what the length of the string that currently exists, an exception will be thrown. For example, if your stringbuilder contains a string length 4 (index 0 to 3), then calling insert with any number higher than 4 will cause an error.

delete(int Start, int End)/deleteCharAt(int index)
Like they say, these functions will delete either a subsection of the string, or the character at the specific index. If you pass in invalid numbers, an exception will be thrown.

reverse()
This doesn’t really need much of an explanation, does it? Call this on the string builder, and the value in it will be reversed.

toString()
This will return the value of the string builder as a string.

Remember that most of these functions when called will return a reference to the string builder that you’re calling the function on, not a new string builder.

Advertisements

Java: Numbers and Numeric Promotion

Numbers, kind of a backbone of, well, most things when you think about it. This post will cover how Java treats typed numbers in code, which are called literals or sometimes also referred to as magic numbers (depending on how sarcastic the person reviewing your code is), and how numeric promotion works. What possible depth could there be to number literals in Java you ask? I’m glad you asked (but I bet you aren’t!). Continue reading

Java: Garbage Collection

Garbage collection in Java is kind of, well, garbage. What is it? It’s the process by which the Java Virtual Machine cleans up no longer used pieces of memory (objects that are out of scope, for example), in order to keep memory free. It’s a bit of an odd beast, though. You can explicitly call it, but sometimes it will run, sometimes it won’t. Continue reading

Java: Variable Naming

Variables are pretty self explanatory, they are used to hold references to points in memory that store information (ok, maybe not that self explanatory). Things like strings, integers, doubles, objects, everything, in fact, can be stored as a variable. They are for the most part pretty simple, but, as always, there’s some odd and confusing edge cases to be aware of when using them.

Continue reading

Java: Class Structure

There may be one or two people who click onto this article expecting a discussion on socialism, sorry to disappoint, but it’s still about Java!

We touched briefly on class structure in the last post, but now I want to dive into a bit more detail on the different components of a java class. Most of it is pretty basic, but there may be one or two parts that surprise you.

Continue reading