String vs StringBuilder vs StringBuffer
In this article, we’ll take a look at the differences between these three classes and their appropriate use cases.
Strings are a fundamental part of programming and can be found in nearly every programming language. In Java, strings are used to represent a sequence of characters. However, there are several ways to create and manipulate strings, including String, StringBuilder, and StringBuffer. In this article, we’ll take a look at the differences between these three classes and their appropriate use cases.
String
In Java, a String is a sequence of characters that is immutable. This means that once a String is created, it cannot be modified. Any operation that appears to modify a String actually creates a new String object.
For example:
String str1 = "Hello";
String str2 = str1.concat(" World");
System.out.println(str1); // Output: Hello
System.out.println(str2); // Output: Hello World
In the above example, we concatenated " World" to the String "Hello" using the concat
method. However, this did not modify the original str1
String. Instead, it created a new String object str2
.