*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.
The StringBuilder and StringBuffer Java classes are nearly identical, but that answer will probably not satisfy an interviewer. The best short answer to this question is that StringBuilder is asynchronous, while StringBuffer is synchronized and therefore thread-safe. To be able to craft a more complete response to this common entry-level Java interview inquiry ? or if you predict that you?ll need to be prepared to answer follow-up questions ? you?ll have to continue reading.
Once you?re further through this article, you?ll learn what these peer classes of String do, how the commands are handled by the processor core ? or cores ? during execution, and why employers might consider this important knowledge. At the end of the discussion, look for a quick summary of the subject and some talking points for you to show off your knowledge.
A Brief Introduction to the Science
Chances are you know most of this already if you?re applying for a software development job. However, if you?re fuzzy on some of these points, that lack of deep knowledge will probably show during an interview. Make sure you?re prepared for exhaustive discussions by reviewing this info: giving quick responses without any context probably won?t be super effective if you?re up against a trained tech interviewer.
What Is a Class?
The definition of a class is pretty basic, but you?ll still need to know it to discuss the differences between StringBuffer vs. StringBuilder. Classes in Java are templates for creating similar types of objects. They contain methods, which are basically ways to do things. Examples of things methods can do include defining an instance of the class or helping you modify data.
Thread and Core Technology
The first step toward understanding the difference between these two classes ? more specifically, why StringBuilder was necessary when StringBuffer was already in Java ? is to understand developments in computer science technology.
The trend towards parallel processing has been going on forever. Generally speaking, this has meant splitting up large problems into multiple smaller sections, whether it?s getting many people to work on constructing a building or a team to put together a multi-course meal in a fine-dining restaurant.
In computer science, one example of this trend is the development of multiprocessing. This involves having many chips wired together, each performing different tasks or parts of the same task. One complete example would be a contemporary personal computer with a dedicated graphics card ? both the CPU and the GPU would probably each have multiple cores in addition to being distinct processors themselves.
Another example is multithreading, which can be carried out on one or more processors. This allows one task to jump in and use resources when another has an issue, such as a cache miss, for example. StringBuffer, however, was not built to take advantage of this type of technology. StringBuilder is asynchronous, meaning that it does not need to be processed directly from start to finish and therefore performs well in multithreaded environments.
Key Points to Consider
Your interviewer is probably looking for a few basic pieces of foundational knowledge if he or she pursues this line of questioning. Here are some things to know about the difference between StringBuilder versus StringBuffer, distilled for your quick reference.
Java 1.0 introduced the StringBuffer class, which was then followed in a later version by the StringBuilder class. If you need a mnemonic device for this, remember that StringBuilder comes after StringBuffer alphabetically.
Executing methods on StringBuffer must be done in order, synchronously. StringBuilder can be processed on multiple threads. This is the defining difference between the two classes.
StringBuffer is synchronous and therefore inherently thread-safe, theoretically at least. In practice, the level of thread safety offered simply by choosing StringBuffer over StringBuilder isn?t usually enough to guarantee the results you want. Furthermore, there would be plenty of better ways to guarantee that your program works as well as possible when multiple lines of processing are knocking away at one resource, regardless of which of these classes you were to use.
StringBuilder is generally faster than StringBuffer, especially in a single-threaded environment. It owes this, again, to its asynchronous properties. Both will almost always be lighter and faster than String when you?re modifying the data they contain.
Both classes have most of the same methods. However, there are a few differences, namely that StringBuffer has several additional methods. At a glance, it might seem like a step backward that these extra methods weren?t included in StringBuilder. However, since they are duplicated by the methods in String, the question arises as to why they were included in StringBuffer in the first place ? a discussion for another time.
Your interviewer might want some practical cases in which you would use each of these. For a legacy class like StringBuffer, your best bet is to say that you would only use it if an existing API demanded it. Otherwise, the best practice would probably involve using StringBuilder. If you don?t see a performance advantage, you would probably find other bottlenecks in the code upon analysis.
Controlling the Interview
If someone is asking you a lot of seemingly basic questions, it?s easy to fall into answering them on reflex. Sometimes, this affects the tone of your interview; it can turn into a sort of call-and-response song. At the worst, you might find yourself rushing through or adopting a patronizing tone. Combat this impulse by taking a little initiative.
Remember that it?s not all about displaying knowledge. There?s a subtext to the conversation. The company is checking you out to see if you?re going to be a good person to have in the company. On that note, remember to have fun during your interview. Keep it professional, but also remember that you?re having a conversation.
The interview isn?t an exam. In fact, there?s probably a skills test accompanying or preceding the interview. Of course, the people on the other side of the table want to know that you know your stuff ? and probably have a formal script that they cycle through with every applicant. Stay on topic when you attempt to control the flow, but don?t be afraid to be interesting. Here are a couple of ways you could riff off of this common StringBuffer versus StringBuilder question.
Mention Previous Experience
If you?ve only ever used String and StringBuilder, you?re not alone. String is ubiquitous in many Java programs. The asynchronous version of StringBuffer has been around for a while, and, as you may have read above, most current applications use it.
If you say that you?ve only ever implemented the first two classes, but that you also remember StringBuffer?s uses, then you accomplish two things. First, you let the interviewer know that you have practical experience. Second, you communicate that you retain contextual knowledge ? a powerful personal asset in the tunnel-vision world of hacking.
Predict the Follow-Up Question
If you haven?t already been asked about the String class, there?s a chance that the interviewer will want you to discuss that next. Mention that both StringBuilder and StringBuffer would allow you to use simpler code and dump less garbage on the heap than String if you?re modifying the variable.
Tell a Story
If you have a good story about how you used one of these classes to increase efficiency, solve an error message or otherwise save the day, now is the time to tell it. Just remember to keep your recollections brief. Whenever you?re telling a story in response to an interview question, think of it more of an illustrated answer than a full recounting of events. Save the expanded version for when you run into your interviewer in the break room once you?re hired.
Mention Community Involvement
Many companies are looking for something in addition to competency in core engineering skills these days ? the ability to work as part of a team. However, simply saying that you?re good working with a team often seems a little too obvious for an interview setting.
Of course, you should offer concrete examples if your interviewer asks you directly about group projects, but you can also suggest that you?re ready to support the company effectively by mentioning your involvement in the larger coding community. Simply preface your answer to this question with a brief statement about helping a friend, or another member of a discussion group, solve a String class issue, for example.
Answer With a Question
This particular question covers a lot of territory, potentially. If you?re confident enough in your knowledge on the subject, you could respond by asking a clarifying question. A good example of this strategy is asking whether your interviewer wants the short or long version of the answer.
This type of response has many benefits when you do it correctly: it saves everybody precious time and effort by giving your interviewer exactly what he or she wants, it keeps your interviewer from going on autopilot, and it shows that you have good interpersonal communication skills. Additionally, even if they choose to have you give them the short answer, you?ve made the implication that you have deep knowledge of the String class and its relatives.
Making a Big Impression
The most complete, concise answer to this question would probably depend on the context. However, you are probably safe if you mention that, while the two classes are almost exactly the same, StringBuilder is newer than StringBuffer and faster because it is asynchronous.