Java Tutorial
IntroductionEnvironment SetupIDEBuild ManagementLanguage SpecificationBasic ProgramVariablesData TypesPackagesModifiersConditionalsLoopsObject OrientedClassesSuperInterfacesEnumStatic importInheritanceAbstractionEncapsulationPolymorphismBoxing & UnboxingConversion Formatting numbers Arrays Command line arguments in java Variable Number of arguments in Java Exception handling in Java String handling in Java StringBuffer and StringBuilder in Java Mathematical Operations in Java Date and Time in Java Regular expressions in Java Input output programming in Java File Handling Nested Classes Collections Generics Serialization Socket programming Multi-Threading Annotations Lambda Expressions Reflections in Java Singleton class in Java Runtime Class in JavaHow to load resource in JavaHow to load properties file in JavaAdvanced
Log4j – Logging framework in JavaInterview Questions in JavaAs you know, String objects are immutable. Every time you create a String object, you can not change it at all. So if you create 1 string object and appended something into it, a new String object is created altogether. This wastes the memory. That’s when StringBuffer and StringBuilder comes into picture. Objects of StringBuffer and StringBuilder classes are mutable. StringBuffer and StringBuilder are also better than String as compared to performance.
Difference between StringBuffer and StringBuilder
So both StringBuffer and StringBuilder are mutable. Which one should you use? Difference between StringBuffer and StringBuilder is that StringBuffer is synchronized while StringBuilder is not. So when you want thread-safety, you should go ahead with StrignBuffer otherwise you should go ahead with StringBuilder. Below example illustrates how to use StringBuilder and StringBuffer in Java.
package strings;
/**
* Created by Sagar on 20-04-2016.
*/
public class StringBuilderBuffer {
public static void main(String [] args){
//StringBuffer should be used when you want thread safety
StringBuffer stringBuffer = new StringBuffer("softpost");
stringBuffer.append(".org");
System.out.println("Using StringBuffer -> " + stringBuffer);
//StringBuilder should be used when you are using single thread
StringBuilder stringBuilder = new StringBuilder("Sagar");
stringBuilder.append("Salunke");
System.out.println("Using StringBuilder -> " +stringBuilder);
}
}
Here is the output of above example.
Using StringBuffer -> softpost.org
Using StringBuilder -> SagarSalunke
Web development and Automation testing
solutions delivered!!