Contents

A Review of String and StringBuilder in Java

   Aug 22, 2023     8 min read

What is String??

String is a special Object class that is implemented by Java. Unlike other data structures like arrayList, HashMap…etc, you do not need to import String from java.utils, because String is specifically implemented inside the java.lang package. If you look at the source code, you will see that in Java 11, inside the String class, there is a public final byte[] as a field.

public final class String implements java.io.Serializable, Comparable<String>, CharSequence
private final byte[] value[];

This leads to some unique properties that String has.

  1. String is immutable, immutable means you cannot change characters internally, for example: “abc” + “d” -> will lead to open a new memory space for a new String
  2. Can lead to index out of bound exception, if you access index over its length
  3. Can lead to null pointer exception, if you access a method in a null object.

How to create a String Object in Java

  1. Directly define method: String a = "abc"
  2. new String keyword: String a = new String("aaa")
  3. intern() method: String s2 = a.intern()

What API do we need to know about String?

The following table is a quick guide that include all APIs you should know about when you use Java for coding interviews. You can find the details of String APIs here.

String APIComment or things need to be aware of
char charAt(int index) 
int compareTo(String s2)This API compare String based on their lexicographically order, \Capital character is greater than non-capital character. \ ABC.compareTo(abc) would return -1, meaning ABC is smaller than abc
int compareToIgnoreCase(String s2)same API as above just without cases
String concat(String s2)same as adding String “+”
boolean equals(String s2) 
boolean equalsIgnoreCase(String s2) 
replace(char oldChar, char newChar)non-static method
replace(CharSequence oldS, CharSequence newS)non-static method
int indexOf(char c) 
int indexOf(String s1) 
int length() 
String substring(int beginIndex) 
String substring(int beginIndex, int length) 
char[] toCharArray() 
String toLowerCase() 
String toUpperCase() 
String trim() 
String repeat(int repeatTime)it concat the same String for repeatTime times

What is StringBuilder()?

StringBuilder is a class that Java implemented to allow user to “dynamically modify” the String. Again, StringBuilder is in Java.lang package, so you can use it without importing it.

How to create StringBuilder in Java?

Just like creating an Object: StringBuilder sb = new StringBuilder()

What API do we need to know about StringBuilder?

StringBuilder APIComment or things need to be aware of
append(char ch) 
append(char[] charArray) 
append(char[] charArray, int startIndex, int length) 
append(CharSequence s)if append null, it will append “null” inside sb
append(CharSequence s, int start, int length) 
append(String s) 
int capacity()Yes just like an ArrayList, StringBuilder has capacity
char charAt(int index)if it exceeds length, it can throw exception
delete(int startIndex, int length) 
deleteCharAt(int index) 
int indexOf(String str) 
int indexOf(String str, int fromIndex) 
insert(int index, String s)it put the String into the StringBuilder, and push the rest of the String back
int lastIndexOf(String)lastIndexOf return the first index of the rightmost occurrence.
replace(int startIndex, int length, String str) 
reverse() 
setCharAt(int index, char ch) 
setLength(int newLength)Be aware of the exact length, if set too much length, it will appear a lot of empty useless charcode
subString(int startIndex) 
substring(int startIndex, int length) 
toString() 

String Processing Interviewing Questions

As the old saying: when you see a question that is String Processing type of question, you will know it is a String Processing type of question. One good thing about String Processing type of question is that it is very easy to identify. Usually this type of algorithmic question is not hard in Logic, but ,most of the time, the question itself is very annoying to cover all cases, and the code can get very long and reluctant as well. If the question itself is asking to implement the above mentioned String APIs, you probably will not able to implement it using StringBuilder(the interviewer will ask you to do it in-place). Here is the summary of this type of question.

  1. ask for clairification first, which character can be in the input String, which characters dont, this is very important, can save you a lot of times from nasty edge cases.
  2. if the problem itself involve integers, ask for signs character.
  3. Discuss different synario case by case, list them out visually.
  4. most of the time, it will utilize two-pointer techniques. left side of slow pointer is what i want to keep for the result, while fast pointer is used to traverse the rest of the String.

Practice Question by topics

String Removal:

Problem NumberProblemSolution
1remove certain character from StringSolution
2Remove SpacesSolution
3Remove All Adjacent Duplicates In StringSolution
4Remove All Adjacent Duplicates in String IISolution
5Remove CommentsSolution
6Remove All Occurrences of a SubstringSolution
7Removing Stars From a StringSolution

String Reversal:

Problem NumberProblemSolution
1Reverse String 
2Reverse String II 
3Reverse Vowels of a String 
4Reverse Words in a String 

String Palindrome Series:

Problem NumberProblemSolution
1Valid Palindrome 
2Valid Palindrome II 
3Valid Parentheses 

String to Integer, Integer to String Series:

Problem NumberProblemSolution
1Integer to Roman 
2Roman to Integer 
3Excel Sheet Column Title 
4Excel Sheet Column Number 
5Cells in a Range on an Excel Sheet 
6String to Integer (atoi) 

String to Math Operation:

Problem NumberProblemSolution
1Add Binary 
2Add String 
3Add String with negative input 
4Multiply String 

String Replace, Modify String Series:

Problem NumberProblemSolution
1Find the Index of the First Occurrence in a String 
2Rearrange Spaces Between Words 
3String Replace 
4Compress String 
5Decompress String I 
6Decompress String II 
7Text Justification 

Split String

Problem NumberProblemSolution
1Split Strings by Separator 
2Maximum Score After Splitting a String 
3 Split a String in Balanced Strings 
4Number of Good Ways to Split a String 
5 Number of Ways to Split a String