Strings, StringBuffer

Strings, StringBuffer

In Java, strings are a sequence of characters, represented by the String class. The String class is immutable, meaning once a string object is created, it cannot be modified. On the other hand, StringBuffer is a mutable class that allows modification of its contents.

Here are some differences between String and StringBuffer:

Immutability: As mentioned earlier, String is immutable, which means the contents of a String object cannot be changed once it is created. On the other hand, StringBuffer is mutable, and its contents can be modified.

Performance: Because String is immutable, every time you modify its contents, a new String object is created. This can be a performance issue when you need to modify a string multiple times. In contrast, StringBuffer is designed for efficient string manipulation, and modifying its contents doesn’t create a new object every time.

Thread-safety: String is thread-safe because it is immutable. On the other hand, StringBuffer is not thread-safe, but there is a thread-safe version of StringBuffer called StringBuilder.

Here are some examples of using String and StringBuffer in Java:

// Creating a String object

String str = “Hello, world!”;

// Modifying a String creates a new String object

str = str + ” How are you?”;

// Creating a StringBuffer object

StringBuffer sb = new StringBuffer(“Hello, world!”);

// Modifying a StringBuffer doesn’t create a new object

sb.append(” How are you?”);

In the example above, modifying the str object creates a new String object, whereas modifying the sb object using the append method does not create a new object.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Share this post
[social_warfare]
Java.lang
Collections

Get industry recognized certification – Contact us

keyboard_arrow_up