String And String Buffer
Strings and StringBuffer in Java
In this article we will be discussing about Strings and StringBuffer in Java.
String is a non-primitive data type of java, non-primitive data types are created by the programmer and the String Buffer class in Java is the same as the String class except that it is mutable, i.e. it can be changed.
What are Strings?
String is an immutable class and its object cannot be modified after creation, but it definitely refers to other objects. They are very useful in a multithreaded environment because multiple threads cannot change the state of an object, so immutable objects are thread-safe.
Example:
import java.util.*; public class Main{ public static void main(String [] args){ //Initializing a string variable String str = "PrepInsta"; System.out.println(str); } }
Output: String str = "PrepInsta"
What are String Buffers?
A string buffer is a mutable class that can be used to perform operations on a string object, such as reversing a string, concatenating a string, etc. We can modify a string without creating a new string object. The string buffer is also thread-safe.
Example:
import java.util.*; public class Main{ public static void main(String[] args){ // Initializing the object of Stringbuilder class StringBuffer str = new StringBuffer("Prep"); // Giving value to the Variable using append method str.append("Insta"); System.out.println(str); } }
Output: String str = "PrepInsta"
Difference Between Strings And StringBuffer
Key | String | StringBuffer |
Basic | String is an immutable class and its object can’t be modified after it is created | String buffer is mutable classes which can be used to do operation on string object |
Methods | Methods are not synchronized | All methods are synchronized in this class. |
Memory Area | If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool | Heap Space |
Performance | It is fast | Multiple thread can’t access at the same time therefore it is slow |
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment