Member-only story
Java String & Important Concepts
String is one of the most commonly used data types in Java programming. Understanding the concept of Strings is crucial for any Java developer. In this blog post, we will discuss some of the important concepts related to Strings in Java.
Immutable vs Mutable Strings
In Java, Strings are immutable objects, which means once we create a string object, we cannot perform any changes in the existing object. If we are trying to perform any change, a new object will be created with those changes. This non-changeable behavior is known as the immutability of Strings.
For example,
String s = new String("softAai");
s.concat("Apps");
System.out.println(s); //softAai
In the above code, the concat()
method is called on the string object s
, but the original string remains unchanged. This is because a new string object is created with the concatenated value, but it doesn't hold any reference in this case, and hence it is eligible for garbage collection.
On the other hand, if we use StringBuffer
instead of String
, we can perform any change in the existing object. This changeable behavior is known as the mutability of the StringBuffer object.
For example,
StringBuffer sb = new StringBuffer("softAai")…