Comparing String with StringBuilder
When dealing with strings, these two classes are your go-to classes. Their primary difference is that String
objects are immutable, whereas StringBuilder
objects are mutable. This means that for strings, once you create a String
object, you cannot ever change that object. Java might make it look like you changed the object but you haven’t; a new object, reflecting your changes, has been created. StringBuilder
objects, on the other hand, are mutable. This means that you are working with one object all the time. We will delve into this with an example later.
Why immutability?
Immutability is attractive from a security perspective as immutable objects cannot be changed. In addition, immutable objects are thread-safe in a multi-threaded environment. In multi-threaded environments, changes to (non-immutable) objects have to be synchronized one at a time so that changes do not interfere with one another Immutable objects are, by definition...