Sunday, 14 April 2019

String, StringBuilder and StringBuffer


Equality

String overrides the equal method, but StringBuilder and StringBuffer don't.

So when a Str reference does an equal check with a reference of either a StringBuilder or a StringBuffer, it will always fail, irrespective, if all references are referring to a same value.

If you really want to check for equality, always use the toString() method on the StringBuilder and StringBuffer references

Demonstrated on below github link.

https://github.com/omerhashmininjago/java-programs/tree/master/src/main/java/com/demonstrate/concepts/string/example2

Concatenation

When a String reference is passed to a method, and we perform a concatenation, the reference with in the method would point to another object, but the original string reference will continue to point to the older object. This is because String is Immutable

This concept will not work for StringBuidler and StringBuffer as they are Mutable, the original reference will point to the newly created object.

Demonstrated on below github link
https://github.com/omerhashmininjago/java-programs/tree/master/src/main/java/com/demonstrate/concepts/string/example3

Thread Safe

When working in a single threaded environment


  • String to be used when we are sure that the string in question is not going to changed
  • StringBuilder to be used, when the string is going to go through lots of changes and we would be using a single thread. StringBuilder is not thread safe
  • StringBuffer to be used, when we would have multiple threads accessing the same string reference and we would need to be sure happens-before relationship is not violated



No comments:

Post a Comment

Volatile keyword, Synchronized keyword and Lock interface

Volatile Marking a member variable as volatile, makes sure, when ever the member variable is accessed, its value is always read from the...