- Podcasts
- The Java Developers Hub
- Java String Methods Explained | StringBuilder vs StringBuffer & Advanced String Manipulation
Java String Methods Explained | StringBuilder vs StringBuffer & Advanced String Manipulation
The Java Developers Hub
- December 3, 2026
- 1 h 16 min
- Episode 32
About this episodeWorking with text is a fundamental part of Java development. Java provides a rich collection of String methods that allow developers to…
- Understanding Java String methods.
- Finding string length using length().
- Extracting characters using charAt().
- Comparing strings using equals() and equalsIgnoreCase().
- Comparing strings lexicographically using compareTo().
- Searching text using contains(), indexOf(), and lastIndexOf().
- Extracting substrings using substring().
- Replacing text using replace().
- Changing letter case using toUpperCase() and toLowerCase().
- Removing surrounding whitespace using trim() and strip().
- Splitting strings using split().
- Checking string content using startsWith(), endsWith(), and isEmpty().
- Understanding StringBuilder and its mutable nature.
- Understanding StringBuffer and its thread-safe operations.
- Comparing String, StringBuilder, and StringBuffer.
- Using methods such as append(), insert(), delete(), and reverse().
- Choosing the right string-handling class for different applications.
- Java beginners learning string manipulation.
- Computer science and software engineering students.
- Backend developers working with text processing.
- Java programmers preparing for technical interviews.
- Developers interested in performance optimisation.
- Anyone looking to master Java String operations.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Java String Methods Explained | StringBuilder vs StringBuffer & Advanced String Manipulation
Yes, so let's start. Welcome back Coder Army to our Java series. And today we are going to go into more depth of strings. We are going to understand what are the methods in strings, what is a string builder, what is a string buffer, what are the differences between these three. And you will have a lot of fun, you will get to know a lot of new things about strings. So let's go to the screen and quickly start. Yes, so we knew that if we want to declare strings in Java, then we have two ways. One is the literal way. And another way is to use a new operator. So if I write a string, string s1 equal to let's say hello, this is the literal way of Java to declare a string. And these strings go to the Java string pool. And the second way is if I write string s2, and if I put a new operator here, new string, and then let's say in the constructor, I pass my object or string, hello. So I know where this string will go. It will go to my normal heap memory. So we know these differences. We know that when we declare a string in a literal way, this is a special syntax that Java has given us. No new keyword is being used from inside. Java knows that whenever we use simple equal to, what do I have to do? I have a special way inside the heap memory, which I call Java's string pool. I will go and store these strings there. Right? We already know all this. Now we have to move ahead and we have to see that in our string class, what are the methods, what are the constructors, how can we declare the string, what operations can we perform on it, etc. So let's start with the methods of our strings. So look, First of all, let's take a look at the constructors of all the strings. How many ways do we have to define a string? And we will obviously do all this with the new operator because obviously when we talk about the constructor, then which format are we talking about? In which we declare the string with the new operator, that is, in our normal heap memory, the object of our string is formed. Yes, so here I have taken my empty project again named demo.java. And we are going to see how many ways to declare our strings. That is, let's see which constructors exist in our strings. So let's see it once. First of all, if we make a string, string let's say s1 and make it from an empty constructor, say new string, new string, okay? And obviously its constructor, I didn't pass any value, then what will happen? Our empty string will be made. What does empty string mean? If I try to print it, system.out.println s1, then what should come on our screen? Let's run it once and see. our screen will be empty. No null, no space, just empty string. Now if I pass something like this in constructor, I just open and close my double quotes, nothing else is written. Now if I try to print it, again empty string. Right? This means, either I don't pass anything here, or I pass my double quotes and leave it. In this way, my empty string is made. Okay, very good. What about a new string, s2, which I make a new string like this. And here, I pass a string, let's say literally hello. Something like this. And if I print s2, then you know what should come on my screen? Hello should come. And my hello has arrived. So this is another way to declare a string. Our second constructor is basically. Your constructors must have a lot of overloads inside the string. One would be the one that doesn't take any value. So I can leave it empty. The second would be the one that takes a string. So literally I passed a string here and I assigned it to s2. Now obviously if I have put a new operator here, then you know that a string will be made. It will be made in normal heap memory and s2' s reference will be variable. Now we also know one more interesting thing, we know this because I have written a string literally here, hello, so this will also be made in our string pool, right? We had seen this before, so hello will be made in the string pool first and then this object will also be made in the normal heap in the name of hello, which will be pointed to S2 and no one will refer to the hello of the string pool because there is no reference to it, right? Okay, what about Let's first make a string, let's say s3, and make it a literal string, let's say aditya. And after that, I'll make a new string from the new operator, and here I will pass S3. Right? I can also do this obviously. In this case, you know what will happen? First of all, Aditya will be in our string pool which will be pointed by S3 and then I have written a new string here that means this object will be in our normal heap and what did I pass in the normal heap? S3 which is Aditya. So, there will be one Aditya in our heap. Let's remove this for now. So, think like this that there will be one Aditya in our heap memory in this case and there will be one Aditya in our string pool. Like this, right? And who would be doing this point? He would be doing S4 point. Something like this here. And who would be doing this? S3 point. S3. Something like this. Right? So we already know all this. So this is one way. Okay. And is there any other way? Absolutely. We can also pass a complete character array. So imagine I have a character array. Let's say ARR. And I have added some of these values in it. Let's keep it like this. So here I have added my full name Aditya. And what did I do? I added a character. So this is my character array. Now if I want I can make a string s5. And I can directly make a new string. And in its constructor I can pass this array arr. In this case, I passed an array of a character and gave it to the constructor of s5. Now it will convert this character array into a string. So if I print s5, then I should get Aditya. Right? Okay, we know that string is immutable. So obviously, it wouldn't have used this character array as it is. Meaning, if I change this array to 0th element where a was written, let's say b. Something like this. There will be a single quote because it's a character. Okay. So, if I try to print S5, will my Aditya print B instead of A? You know that it won't happen. If we try to print it, it will print Aditya again. Why? Because we know that our string is immutable. No matter how much we change in the original array, it won't change in this S5. Because it has obviously copied the data. You know that in the string class, there is a value called values. In that array, it would not have copied the values as it is, but would have made a new array. Now obviously you know that it is a byte array and not a character array, but in the old Java, there was an array of characters. Okay, now there is another version of this character array. Let's say I don't want to use this entire character array for my name. Let's say I have shown my surname here. So see what I did now. I changed this character array and wrote the entire Aditya Tendal. So let's say we put a space here so that a space comes between these two. So we leave it empty and Something like this. So I wrote aditya space tendon like this. Now if I try to print s5, then my full name should be on the screen and it should be there. Now if I want, then I can use only one part of this character array. How? What if I write like this that I am declaring a new string s6 which is equal to new string new string And here I want to use this array, but I don't want to use the entire array. So look, I have another constructor here, which takes three fields. One is the name of the array, and its starting value and its ending value. Starting value means its index. Let's say I want to use the index from the 0th index. 0, 1, 2, 3, 4, 5, 6. So let's say I want to use up to 6 indexes. Something like this. So see, as soon as I wrote all three values here, one is my array, one is offset and one is count. So let me tell you which constructor is overload. First, I remove this too so that my array doesn't change. And now I print our S6. Something like this. Okay, let's write S6 here. Now if I go to the screen and check, then what will be my print? My print will be only Aditya. That means if I want, then I can use a small part of a whole character array to put in my string. In that case, what I have to do is pass my original array character and its starting index and ending index. I call the starting index offset and the ending index count. It must be saying that from inside. That's why it's showing in IDE. If I hover this up and go to my string class, string.java, So this is my constructor which takes an array of characters, an offset and a count. Before this, if I go to this string constructor, it takes only a character array. So look, it takes only a character array, the offset is 0 and the count is value.length. which means it tries to store the entire array. Right? So we can either store the entire array using the normal constructor or we can pass our offset and count ourselves. So here I have passed 0, which means the starting index is 0 and 6. And which index is 6? It is this index. So 0, 1, 2, 3, 4, 5, 6. Okay? Now you just have to remember one thing. Whenever we write 0, 6, the first index which is 0 is inclusive, which we write here. And this last index which we have written here, 6, is exclusive. You must have read in Maths that we show inclusive like this and exclusive like this. So I can write like this 0, 6. Where my square bracket is telling me to include 0th index. And this parenthesis is telling me to exclude 6th index. Means we have to take everything from 0 to 5, not 6. So this is the way of Java to tell us how to print it. Okay, so if we know all these methods, there is one way to make it empty, one is to pass a string, so I write that I directly passed a string in the constructor, a character can be passed, a character array subset. So here we write character array subset. There is no other way. Think about it. In our string class, the string stored is in an array named values. We have read this. There is an array named values in which string is stored. And we know that the data type of the array named values is byte. It means that actually our string stores the characters from inside in bytes. It means that it stores its ASCII or Unicode values. Right? So why don't we use our character array and use a byte array to make a string? Is it possible? It means that let's say I have a byte array, not a character array. I keep it as ARR2. And here are some values. Now see this is ARR2, it is a byte array. That means it will want to take some numbers. Here if I give some ASCII values or Unicode values. So let's say I gave 97, 98, 99. Okay. Here I wrote 91, let's do 97. Yes, 97, 98, 99. So I know 97 means small a, 98 means small b and 99 means small c. Right. So now if I see and make a new string. String, let's say, which number is running? Let's make S7. s7 equal to new string and here I pass this arr2 ok so let's see how my string will be made so I will print this system.out.println I have written it wrongly println s7 something like this ok so let's comment this for now ok So, if I run it, then my string is ABC, which was expected, right? So, basically, we can also use a byte array to make our string. Obviously, we can also give an offset and count in this byte array. So, I said, start from 0 and finish at 1. Or, let's do one thing, finish at 2. Obviously, we haven't read about them yet, but you can expect that we will read about them later. So, let's say I have an object named StringBuilder. Let's call it sb, equal to new StringBuilder. And suppose I have a string here, let's say hello. And if I try to make a string from this, let's say s8 equal to new String. So I can also add a string builder object in its constructor, sb. So my string will also be made from there. So if I want, I can print it. And this is my s8. And I comment s7. So my hello print should be on the screen. So let's run this once and see. Right, in fact, instead of string builder, I can also write string buffer. Buffer, not builder, buffer. Yes. So, I have to do the same thing here. I have to make a string buffer object. So, I have to make a string buffer object. And how did I make S8 this time? New string SB. SB means string buffer. So, I have passed the object of string buffer. So, now if I run this, then my hello will be printed again. So, my constructor can basically take the object of string builder or string buffer. We will study further about these two classes. So these were the overload methods of my constructors. Empty constructor, take a string, character array, byte array, string builder, string buffer. Obviously, in both of these, I can take a sub-string or basically I can take a sub-array. We saw this too. Cool. Now let's see what methods we have in the string class. Before that, let me tell you that there are a lot of methods in the string class. Obviously, we don't have to memorize all of them. We don't have to connect them emotionally with the syntax of any language. What we have to do is, we have to see which are the important methods. Basically, we will read them groups-wise. We will take a look at them. But whenever you work on IDE, you know that if you have a string, let's say string s equal to new string. You have something like this. So whenever you write s dot, you know IDE suggests you the methods and lists them down. In fact, some methods have overloads as well. So there is only one method which has multiple overloads as well. So we don't have to memorize all of them. If we start memorizing them, we will have 30-35 methods which we have to memorize. So we never do that. We just understand the basic things that which operations can be performed on a string. If we don't have all the methods of string, then we have to write the code manually So let's say we have a method in string called reverse, it will reverse the whole string So if you have written hello, it will convert it to OLEH You can also write the code to convert it, but java has already written a code and put it in a method called reverse, you call it and your work will be done Now, Java has already written a lot of methods with the same purpose that you may need all of them. So, let's take a look at the whole group first. What are the methods that we are going to see one by one? So here I have mentioned almost all the methods, all the main methods in a string class. And I have divided them into groups, to find out a length or emptiness, to access a character, for comparison, for searching, for data extraction, for conversion, and some advanced methods. So let's go directly to the code, let's use these methods directly and see what these methods do, and our work will be done. And as I told you earlier, you don't have to be afraid of seeing so many methods, they are in the string class. Most of them will be of your use, most of them will not be of your use. If you want a particular method of your use, you have to see if it already exists in the string. So let's say you have to convert any string to uppercase. So we have a method toUpperCase which already exists. Now whenever you use them in code, some methods will automatically sit in your mind that yes, These are the basic basic methods that you must be knowing. To find the length, to find the isEmpty, to find someone's index. There are some very basic methods. And there are some methods that when you have to use, you will see that yes, they exist in my string. You will get a little idea about it. But you don't have to memorize them. Yes. So look, I have again kept my demo2. java file. We are going to see all the methods of our strings, which we had seen one by one. And again, we will see them group wise. So first of all, we see the methods of length or emptiness. What are they? Before that, let me make a string. So let's say I have a string here, string s1 equal to new string and here I have taken aditya, something like this. Now these methods are very common, you will know by using them. Now suppose if I want to print the length of this string. So let's say println, what is the length of this s1? So I can write directly s1. length. Here my length should be printed. Now you see, in array we used to have a field named length. So we used to write array.length without parenthesis. But in strings, length as a method exists. So we need to put. length method. Now if I want to print length, I can also check if my string is empty. So I can check s1. isEmpty. Will it return true or false? In this case, what will it return? False. That my string is not empty. Now again, apart from this, I have one more method which looks like isEmpty. I call it s1. isBlank. Now isBlank will also ask if my string is blank or not. Now in this case, if it is not blank, then it should come here. False. Now let's understand the difference between these two. This blank was added in java 11. Let's say I have an empty string. In that case, my isEmpty will be true. And my isBlank will also be true. And the length will be 0. So if I run it. But suppose I have only spaces present in the original string. So I have given 5 spaces. So what will be my length? In this case, I think my length will be 5. And will my isEmpty be true? Not at all. IsEmpty will say false because I have something right now. But my isBlank will still be true. Because my string is still blank. I haven't written any character. This blank says that if there is something other than white spaces, then only I will assume that there is something in the string, otherwise I will say that there is nothing in the string. Okay, so let's see if this is the output coming. The answer is absolutely 5, false, true. Okay, so I hope you understood this. Now apart from this, let's go to the next group, which is our character access group. Okay, so you know what our string is. First, I store my normal string here, Aditya. What is a string? It is an abstraction on our character array. Now we have understood that we use byte array instead of character array in Java. But no matter which array we use, we are using an array after all. What is there in byte array? Its ASCII or Unicode values are stored. If it is an array after all, then it will also have indexing. So if I print system.out.println And I have a method called s1. careAt So as soon as I write this, now I have to give an index here, let's say I give index 2 So java will tell me which character is on my second index So first index is 0, then 1 and then 2 Means what should come on my second index? i should come So let's see, before i gets printed, I will comment this Okay, so I have run it and my answer is i. So I hope you have understood what care add is. Now I have a method more interesting than this. And that is s1. toCareArray. Now you must be understanding by name what it does. It converts the whole string into a character array. So if I hover over it, its return type is character array. So if I want, I can take it in character array arr. So you can understand what it is doing here. It converts into a character array. So what will I get? First a will come to the first character, then d, then i and so on. Now let's move on to our third method which is our comparison operators or comparison methods. Now if we want to do comparison, we have to do it on two strings. So let's say I take one more string, S2. And I leave the same value to Aditya. Now the first method of comparison is very interesting and you have seen it many times. Which is, if I write, is S1 dot equals? not equals ends with equals hai S2K. Right? Now why is this equals method interesting? Because we have seen this many times. We know that equals method comes from object class. If you don't know what object class is, then click on the i button. I will attach the link of the video. It is a very important class of Java. So equals method comes from object class. And what does equals method do in object class? You know this equals method. It uses our equal equal operator from inside. That means what do these two do? They just compare our references. They compare references. Okay. Instead of comparing their values. Now S1 is referring to a different object. New string Aditya. And S2 is referring to a different object. So the references of these two are different. Meaning if I write S1 equal equal S2. Then my answer should be false. Right. We know this. But, what our Java has done, String class specifically, has overrided this equals method, so that we can compare the values, not our references. So, if I write s1. equals s2, then the answer should be true. So, in this case, first let's check if our references are different. They should be different. The answer should be false. Here, the second one is false. Okay. Let's remove this, so that it doesn't print again and again. But, now if I write s1. equals sorry, dot equals s2k, then our answer should be true. Something like this, right? So let's print it and see, the answer should be true. Now, as soon as it is equals, in the same way, we have another method, which we call equals ignore case. This is also very simple, you must be understanding by the name. Equals ignore case. Now I have taken S2. Okay. What does it do? It compares S1 and S2 by ignoring their cases. So let's say if everything was written in capital. Okay. If everything was written in capital. So this would give us true. Because they are still equal. Because we ignored their cases. But this upper one would give us false. Because this simply compares them. Okay. So now if I see them. So see first false, second true. Okay. So I hope you have understood this too. Now the third one is a very interesting method I will write system.out.println And I will call it as s1. compareTo compareTo s2 Now what is the meaning of compareTo? Let's understand it first compareTo says that I will compare these two strings First I will change the string First the string is abc and the second is abd So you will see which string is bigger in this abc and abd Now what is big and small in the form of strings? So in the form of strings, big and small means Lexicographical comparison. Lexicographical. Graphical comparison. Now, what is lexicographical comparison, brother? Look, this is the comparison which is used in our dictionary. Okay? If you have seen the dictionary, you know that first ABC should come or ABD should come. The answer is ABC should come, right? Now, A and B are the same, but C comes before D. So, ABC will come first overall ABD. Okay? So, in that case, I will say ABC is smaller than ABD. Okay? I hope you understood this. So, this is lexicographical comparison. Now, compare to. Compare to method. Now our compareTo method will give me an integer output. Either it will give me an output in negative, or in 0, or in positive. When will it give me an output in negative? If my S1 is smaller than S2. When will it give me 0? When both are equal. And when will it give me positive? When my S1 string is bigger than S2. Now, how much negative and how much positive will depend on it? How much difference is there between them? Now, if you see, this ABC string, which is S1, if I take out the values of its ask, then let's say A is stored in 97, B is stored in 98, so I plus it, let's say C is stored in 99, something like this. So, it will get a number, same ABD will get some number. If I subtract those two from each other, then I will get a negative or positive value. According to that, I decide this. So if I am comparing abc and abd, s1. compare2, and abc is smaller than minus 1, so my answer should be minus 1. If I run it, then the answer is minus 1. Okay, what if abd was here instead of abe? So now let's see what my answer is. Now, my answer is minus 2 because it is smaller than both the factors and so on. Okay, now you can understand how the compare to method is working from inside. So, it will compare the ASCII values or Unicode values of these two. And it will give the smaller or bigger ones in minus, positive or plus. If these two strings were equal, A, B, C, then my answer would always be 0. Right? Because there is no difference between the two. So, I saw that the answer is 0. Absolutely right. Now let's move on to our next group Which we call searching So if we want to perform a search in a string So I'll write Aditya again here So how can we do that? So let's say the first method that comes in it That comes contains So I'll write s1. contains And what does it expect from me? It expects a string from me So it says that in this Aditya string If you want to check if there is any other string or not So how can you do that? Let's say I want to check That ity Does my aditya exist in this string or not So the answer should be true Because ity exists So let's see if the answer is true or not Now the answer is true. Now I will close this because it doesn't print. Now the answer is true. Now you know what contains does. If I go inside it, it is taking care sequence object. We haven't studied what care sequence is. If I go further inside, it is an interface. So basically java has made an interface from inside to work on strings. Now, apart from contains, we have many more interesting methods. One is indexOf, so I can do s1. indexOf, and let's say I give a character here. Suppose I want to print the index of i, so I give i here. So as soon as I give i here, what will it tell me? First index is 0, then 1, then 2, i.e. the index of i should be 2. So it should come here, 2. Which will come now, if I run it, then my first will come true, and then 2. Do you know why true will come? Because of this, it will come. Very good. But as soon as I started writing index of, I got so many overloaded methods. I used this one here. I gave a character, let's say C or let's say I. So if I go inside it, it expects a character from inside, but it expects it in integer form. It can do that. If I put a character here, it can put it in the integer. Because integer is a big data type. So type casting can be done easily. Why do we expect integer? Because it stores everything in integer. Okay. If I want, I can pass an integer here and pass a complete string. So let's say I passed ity here. So I want to know what is the index of this ity. Index of ity. But what is the index of a complete substring? From where that substring starts. So it starts from i. 0, 1, 2. The index of i is 2. So the index of ity is also 2. So, it should be true here as well. So, if I look at it, my output will be again true. Now, you can see the other overload methods one by one and see how they work. But the main thing is that you should know how many methods strings have overloaded. As soon as this index of works, we have other methods like lastIndexOf. You must be able to understand by the name, s1. lastIndexOf. Now I can see the last index of ity. Last index means, suppose ity is repeated. Again, ity is written in front of Aditya. So it will see, ity once, ity twice. So it will give me the index of this i. Because it is coming last time. So its index is 0, 1, 2, 3, 4, 5, 6. So here the answer should be something like 6. So let's see that. Absolutely 2 and 6. Okay, very good. Now like the last index of, now I have two more methods. Starts with and ends with. Now you must be understanding this by the name. What will starts with tell? That s1 dot Let's say starts with. That my S1 starts with a particular prefix. Let's say AD. So the answer is absolutely true. My AD starts with AD. And ends with will tell if it ends with a particular index. Right. You can see that too. Now let's go to our new group. Which we call extraction or transformation. Now see. First of all, here comes our very interesting method, which we call substring. So I will write s1. substring. Now what does substring say? Substring says that I have originally a string, from that I have to remove a small string. And which index to which index I have to remove, I will tell you that too. So let's say I have to remove a string from the first index to the fourth index. So what is the first index? 0, 1. From D to the fourth index. What is the fourth? 2, 3, 4, till y. So, I have to find a string from D to Y. So, I passed the beginner index and index. Now, the interesting thing is that when I give starting index and end index, then it does something like this. This is our substring method. In this, the starting index is inclusive and the ending index is exclusive. We must have read this in maths. Inclusive means we will include the number which we show in square brackets and exclude it in parentheses. So, when I am writing 1, 4 here, then 1 index is included and 4th index is excluded. So, 0, 1, 2, 3, 4. 4 index is y. So, from y to 1 and starting from d. So, my answer should be d, i, t. DIT should come here, so let's print this, before that I have done all this comment Now let's print it and see, the answer is DIT Now my substring is overloaded, again when I will write substring, you will understand that there are two overloads One you can pass beginner index and end index, one you can pass only beginner index, so let's say if I write simple here 1 So what will it do? It will start from 1, that is, it will start from D and go till the end. So it will take D, I, T, Y, A. So let's print it and see the answer is D, I, T, Y, A. Okay? Absolutely correct. Now again, we have many more methods which are very simple. One is your S1 dot. to uppercase which will convert a string to uppercase. So, as you have written aditya, it will print it as capital aditya. If you will print it, it will come as caps aditya. Similarly, we have to lowercase, it will print it as lowercase. Now, we have a very interesting method, trim. So, if I write, let's say, s1 dot So what does this mean? Suppose you have a string in which there are a lot of spaces in the beginning and a lot of spaces in the end So s1. trim trims all those spaces. So basically when it prints this aditya, it will print without spaces in the front and back. So if I run it, you can see my aditya is printed without space. And my s1. 2 uppercase aditya is printed with space. See how much space is there, then aditya started. So it trimmed the spaces for me. But it doesn't trim the spaces, it just trims the spaces in the front and back. But suppose I have some spaces in the middle. So it never trims it. Because it thinks these are important spaces. The spaces in the middle are not trimmed. The spaces on the sides are trimmed. Now in the same way as I have a trim method, I have another method which I call strip. And it also works the same way as trim. But when do we use strip? See, strip is unicode friendly. This means that whenever we know that our characters are going outside the ASCII value, then the strip will be able to trim them properly. If the trim does not work properly, then we will use the strip there and you know that if they come inside the ASCII value, then you can use the normal trim. Now we have another method. Repeat Now this is a very simple method S1. repeat Let's say 3 times So you must be understanding what I want to do I am saying that my name is Aditya Repeat it 3 times and print it on the screen If I comment it Then I should have Aditya 3 times on the screen without space Which happened You can write code by yourself You must be seeing that there are many such methods Which you can write code by yourself But Java has given you that if you want then you can use it directly Now we have one more method which is replace Now see, as I wrote replace, I got two overloads. Now what does it do? Let me tell you. Replace says, you tell me, if you want to replace one character with another character in this string, then I will do it for you. So let's say I said, I want to replace I with O. Sorry, with O. Something like this. So it took old character and new character. So I replaced I with O. So A, D, O, T, Y, A. Something like this will happen. So let's say I print it and see. So my answer should be A, D, O, T, Y, A. So as soon as I run it, it comes back to the same. So this was the first one. The second one was, if I tell it that I want to replace a string, let's say ity, with abc, then I can do this too. This is my second overload. So I want to replace this part with abc. No problem, it will be done. So now if I run it, then see, the part of ity is repeated with abc. Okay. Now, as we replace, we have another method called replaceAll. Now, what does replaceAll do? It removes all the occurrences. For example, I want to replace all the occurrences of a, b, and a, d with a, b. So, it will do that. So, what is a, d? It is the one to be replaced. And what is a, b? It is the one to be replaced. So whenever it will see AD, it will convert it into AB. Right now it is only one, so it will do it only once. But if it was multiple, it would have done it multiple times. Okay? So if you understood replace, then you will also understand replace all. Now look, we have two very important methods. Okay? One is split and one is join. Now look, what is this? This is very interesting. You imagine, you have a new string. Let's take string S3. Okay? And what comes in this string? A lot of names come. Let's say you have a name Aditya. Aditya. Then comma, then another name, let's say Rohit. Rohit, comma, then another name, let's say Rohan. Something like this. You get a lot of names, comma separated. And if you want a string which has a lot of names, comma separated, you make an array of a string which has every value as a name. So first is Aditya in the index, second is Rohit, third is Rohan. So you will call a method on this s3, you will write s3. split So as soon as you write s3. split, it will expect an argument from you where you will give a delimiter. Delimiter means what to split. So I am saying to split with a comma. So whenever you see a comma, split our string. Now see, as soon as I hover over this split method, you see whose return type is string array. So this gives us an array of string. Let's say ARR. Okay, ARR will be declared above. Let's comment this. So ARR is equal to S3. split Now if I print all the elements of this ARR So let's say I use for each loop For each S in ARR And I do system.out.println which is inside this s one by one. So let's see what gets printed. All my characters should get printed. Let me show you. Rohit Rohan. Right. So this is the work of this s3. split. And this is very useful when we understand web development. Because suppose you are getting a very big string. Comma separated. You have to separate all the strings from any delimiter. Here we have used delimiter as a comma. But suppose if everything was full stop or hyphen, something like this. So I could have written hyphen here. Separate all these from hyphen. Then also our work would have been done. See, absolutely right. So basically this is very useful, very important function. You should remember. Okay. Again, there is another important function which is join which is completely opposite to this. Now, the join function is a static function. Meaning, we will call it using class name. So, we write string.join. Now, what does it expect from us? See, it expects us first of all that which delimiter you have to join. Let's say, I have to join with hyphen. After that, you put the list of all strings which you have to join. So, let's say, I have to join echo. So I have to join these three strings with hyphens. So I am expecting that I should have A-B-C. Something like this. Now I am just joining it and not printing it. So let's write the whole thing in system.out.println. Something like this. This will come out. So see that I am getting the same output that I am expecting. Absolutely. a-b-c. Now this is also very useful. This is a matter of work. Again, when we read Spring Boot, you will understand. Many times what we do is, we use multiple strings to make a key. And how can we make a key? I said, take one string, take the second string, take the third string. And by doing a-b-c, we made a key which is unique. Right? This is very useful. Strings, our split and join method. Now if you understand all this, So we have the next category of conversion. Now this is very simple. It says that if you want to convert from another data type to a string, then what method do you have? So suppose I declare a string, s4 equal to new string. So if I have written a new string here and I want to store 10 in the string, then can I write 10 directly in the constructor? The answer is no, I don't have any overload which takes an integer value directly. So I will have to call a method, static method. String.ValueOf And here I can pass 10 So this valueOf method If I hover over it It expects an integer and returns a string Which means it returns the string part of 10 and puts it in s4 Now s4 will be pointing at string 10 Now you must remember when we saw wrapper classes We saw that integer also has valueOf Right? It's exactly the same It's converting a primitive integer into a string It's converting a primitive int into an integer Okay Now another interesting method is getBytes. For example, we had a method here, where did it go? Here it is, toCareArray, which basically converts a string into a character array. We have another method, s1. getBytes. GetBytes. What does it do? It converts our entire string into a byte array. So it's very interesting. If you want to know what are the unicode values of every character, then you can use bytearr equal to s1. getbytes. Now if you print this arr, let's say I wrote for every byte i in arr and let's say I'll do one thing system.out.print i plus let's say comma. Let's separate it from comma. Something like this. So in this string, whatever the bytes are in Aditya, I'll get all of them. So if I run it So look, 6500, 105, 116, 127, whatever the values of ask are, I will get them from inside. Okay? So this is also a very useful method. Now, let's come to our final few advanced methods. Okay? Which are our two main ones. One is our intern. And one is our format. Okay. What does intern do? It is very special. Okay? Let me tell you this. First, understand it like this. Let's say you have a string s5. Okay? Equal to new new String and in this let's say hello So you know what will happen from inside? From inside my S5 reference variable which will be in the stack And new string will be stored in the heap And in which heap will it be stored? In the normal heap This one is hello because normal is a literal So this will go in the pool too But my object will also be made in the heap So this means If I have two things, let's say I have two things One is I have String pool And I have one heap. Something like this. So, as soon as I write this, string s5 equal to new string hello. So, my first hello will go to string pool. You know this. And if there is new string, then my first hello will go to normal heap. And who will be pointing this normal heap? S5. Something like this. Right? You know this. And no one will be pointing at this string pool hello because I haven't pointed at any reference variable yet. Okay. So, this is the current scenario. What if I write string s6 equal to, again, S5. So I wrote it like this. So I said S6 will also point to the same person whom S5 is pointing to. So what will happen? In my heap, there will be one more variable S6 and that too will point to the same hello. In fact, I should write like this that let's say I have a reference variable S6 and that too will be pointing to the same hello. So if I write here system.out. println s5 is equal to s6k. If I compare references with equal operator. Let's comment all these. So my answer should be true. You know this. Let's compare and see. Answer is true. Now what does intern method do? If I write s5 dot Intern. Okay. So, what does this mean? This means that I am saying, the reference variable which points to S5, basically hello, bring that in our Java string pool. If it is not there already. And S6 will point to that string pool variable, string pool object. So, this means, some scenario was like this. As soon as I wrote S5. intern, it will say, S5 points to this hello string which is in the heap. Copy this from the heap and put it in the string pool if it doesn't already exist. But in the string pool, we saw that hello already exists. No problem, we won't put it. And what will S6 do? Now it will move from here to here. Basically here Now it will point this hello in the string pool Now as soon as it will point this hello in the string pool So I will say that now S5 and S6 Both have different references S5 is pointing the memory in a heap And S6 is pointing the memory in a string pool So now if I will do S5 equal to equal to S6 Then the answer should be false So this is the only work of intern, if you want to bring any object in your java in string pool, then you use intern. Why would you want this? There can be many reasons. You are assuming that there is a lot of memory in my heap because you know that whenever I write a new string hello, a new object will be created. But if I do intern, then it will come in string pool and memory is shared in string pool. I hope you understood it. Now, we have one last method which is very interesting which is format. Now, what does format do? To understand this, I will give you an example. Let's take two more strings. Let's say I have a string named name and here it is written Aditya. And one integer is age and let's say it is written 28. And I am telling you, I have to print something like this on the screen. Hello, whatever is the variable in name, let's say for now Aditya comma your age is and the variable in age which is 28 we have to print something like this on the screen so how will you do it? you will write system.out.println which we have been doing till now we used to write first we will write hello hello then we will write let's say plus then a little space then our name will come here Aditya will come then plus then we have to put comma Then we will add a space after comma Then we will add your age is Then we will have another space Then we will have number, our age We will write something like this Now if I run it and let's comment all the above So let's see how the output comes. So my output will be like this. Hello Aditya, your age is 28. But you can see that this is not readable at all. There are so many concatenations. Our format method is useful here. What does it do? I'll copy paste it down. I say we don't need to write so much. We can format it. So, I have a method string.format. Again, this is a static method. That's why I am using string on the class. Okay. And I write here whatever line we want to write. Okay. So, I have to write hello. Then I will get a name. Hello Aditya. Instead of that, I will leave percentile s. Comma Your age is, then my age will come, again I will leave percentile s instead of it. So see how readable it is now. Hello percentile s, your age is percentile s. Now whatever I have to fill in this percentile s, I keep writing comma separated. The first one will come in name, the second one will come in age, something like this. Now again there will be some mistake here, this will come inside this. Something like this. Now if I print this, then also my same output should come. Hello Aditya, your age is 28. It's the same. But now it's so readable. I don't need to do all these concatenations. I'll just write Hello % s, your age is % s. And I'll pass their values ahead. The first one's name, the second one's age. It will automatically fill them in order. So I hope you understood all these methods. We've gone through them once. Again, you don't need to remember them. You can just see which methods exist. After that, how many of its overloads exist? When you use them in real applications, you will get your own things. We don't need syntax. We can google syntax anytime, we can ask. But we have to understand which operations can be performed in a string. Now let's move ahead. And let's see that we have almost read everything about strings. But the biggest problem with strings is that it is immutable. Now again, this is a benefit and also a problem. The benefit is that since it is immutable, it cannot be changed. That means we can use it for passwords, hashes, etc. We know this. But the problem is that since it is an immutable string, whenever we call any Java string method, it creates a new string. Right? So we saw that again if we have this heap and this is our stack and here we have a string let's say hello and here a reference variable named s will point it so whenever we will change anything in this hello let's say I did it in uppercase so what will happen my new string will become hello in uppercase something like this and it is possible that s will point it and stop pointing it Something like that. But again, what happened? I got a new string. Now, if I perform some other operation, a new string will be formed. If someone else, a new string will be formed. So, like this, my memory keeps on filling up. So, being immutable, this is a very big problem. Now, Java has solved it by giving us two such classes which are mutable and work on strings. Okay, which classes are they? One is, we have string builder. String builder class. And one is, we have string buffer class. Okay. Both of these classes work on our string and both of these classes are mutable. Mutable means they change things within the same string. Now what is the difference between these two? The difference between these two is that our string builder class is not thread safe. What does thread safe mean? If multiple threads are running, then multiple threads can be entered in a critical section of it. Which we will see in the thread section later. And this is our thread safe. This is our thread safe. Now these two inherit from a parent class which is called abstract string builder. This is the hierarchy of our StringBuilder in Java. One is our Main Abstract StringBuilder, from which two classes come out. One is our StringBuilder and one is our StringBuffer. Whatever is in the Abstract StringBuilder, StringBuilder and StringBuffer easily inherit it and override it. So again, if we read these two, then you will understand it completely. Now where do these exist? Again, they exist in the same package So you know that you have the java.lang package In that, we had the string In that package, we have the string builder and the string buffer So let's see the string builder first Since they are the same, you will understand the buffer as well So we don't have the class of the string builder from inside So it would look something like this Class string builder And I told you that it extends from abstract string builder. So extends abstract string builder. Something like this, right? This will be its signature. Now what will be inside this? Look, inside this, first of all, we have an array of bytes. Again, this is exactly the same as it used to be in our string. Right? What did it do? It used to actually store data in the form of bytes. So if we have a string java, then the value of j will come here, the value of a will come here, the value of v will come here, and the value of a will come here. We already know this. Okay? Okay. Now the second thing we have, what does it store? It stores an int count. Now you will understand what is count. You will remember, in our normal Java, the string class in Java, class string, in that, apart from these byte values, there was one more thing. Okay? If you remember, which we used to call coder. Right? Which told us, which coder format is it. Whether it is Latin 1 or UTF-16. Right? We understood this. In this case also, coder is there, but it is internally used. Okay? It does not expose Java. So, in string builder class, it is not exposed. It is internally used somewhere. But, the main things we have are values and our count variable. Okay. Now, what is count? First of all, you know what are byte values? It stores actual value. It stores in byte format because it is more optimized. Our data comes in less space. Now, before understanding what is count, you have to understand how string buffer works from inside. So, imagine I wrote string builder and let's make an object of it. Let's say, sb equal to new string builder. New string builder. Okay. And I passed a string in its constructor So let's say I passed the string as java So what will happen? Now I said string builder Because we have mutable Mutable means It will change things in the same string So it does something from inside What does it do? It keeps the buffer of the array of values a little bigger So 1, 2, 3, 4 In this we will get java So here we have J A V A. Now obviously you will say that J A V A will not be stored here, its ASCII values will be stored. But for now, assume that it has ASCII values here. We have not written it, but for now I have shown it with a character. But apart from this, it also has space inside it. So there is a lot of space available here. Something like this. Now why is this space? This space is because if I write tomorrow that I have to append something more in front of java in this sb variable So I have a method called. append, we will see that now So if I write sb.append is cool, this is a string java is cool, I had to write that so I appended in sb is cool So I am expecting that my string in sb will be java is cool And since I am using string builder, I want to change my is cool to a new object. That's why it has taken a buffer here. So what will it do? It will put is in this buffer. And here, c o o l cool. So it has left this space. Okay. Very good. We understood. Now, our two variables work here. One is count and one is capacity. Okay. Count tells us how many places we have stored some values. So in this case, count is 4. Let's write it clearly that our count is 4. Because we have utilized 4 places. So whenever we fill a new character, our count will be updated. Now what is capacity? Capacity tells us the capacity of this whole array. Including these empty spaces. So our initial capacity is 16. Okay, so as soon as we make an object of a string builder, we get an array of 16 size. Java says that you can store whatever you want in it. As soon as it starts filling the capacity, I will again double its capacity, I will increase it. So let's see how it works. So let's say I wrote like this, string builder sb equal to new string builder. So as soon as I made this object, you know, because I have written new here, then an object will be made in heap memory. In that object, which object will be made? Obviously, that string builder type object will be made. And what do I have in string builder? There is an array of values. So what does it do? It obviously keeps it very big in the starting. And I told you how big it keeps it. Now let me tell you. Let's say this is our 16 places. So initially it has chosen the number of 16. And it tells you to do whatever you want to store in the 16 array. So let's say you store something. You first stored Java. Then you wrote sb.append. Then you append something in it, let's say is cool. Then you append something else, sb.append. Now you are again and again appending something in it. Append means you are writing something in the last. So our array will start filling. Some values will come here. And while doing this, some values will come here. Now it says that as soon as my array is full, I will double its capacity. And what is the actual formula? The initial capacity is initial into 2. Plus 2. It also does plus 2. This is its own formula. So, as soon as we fill the space of 16, it doubles its capacity. What does it do? It makes a new array. Something like this. Okay? And what is its capacity? Previously, it had 16. It doubled it to 32. Plus 2. So, its capacity is of 34 places. Now because its capacity is of 34 places So it copies the 16 places array So again here also we get the same things that were here before J came, A came, V came, dot dot dot Whatever was here, it came And the rest of the space again remains empty To append something else Now suppose when this will also start filling up Tomorrow people have filled some things here as well So again it will double this as well So what will it do? 34 into 2 Plus 2 So how much will this be? 60, 70 right? So now it will create a new array of 70 size, it will copy this array and again we will have a lot of values empty. So this is how our string builder works. And string buffer also works the same way from inside. What I mean to say is that it uses a buffer. So you can see what we are doing here. We are using the buffer. And what is the buffer? This array. Which we can also call dynamic array. Because as soon as it fills, we double its size. As soon as it fills, we double its size. And this is done internally by itself. You don't have to do anything. You can just keep writing sb.append. Okay. This whole work is handled by itself. Now obviously you must have understood why it is doing this. Because it wants me to create a new object. And keep on appending things inside the same object. Right. Now if you understood this. So let's quickly see which constructors are present in our StringBuilder. We have already seen our empty constructor, new StringBuilder, and we can leave it completely empty by doing something like this. So again, what will happen? We will have a heap memory, in which there will be an object of StringBuilder name, and we will have a stack memory, in which, let's say, I will call it s. So reference variable name is S and it will refer this. Now we have two things in this, one is values array and one is count. We have seen this in the class. The second way of our constructor is to give a capacity initially. So I will write new string builder. And here I have given the capacity, let's say 50. So I have told you that initially the values array will be of 16 size. But I have told here that I want the size of 50 size. So now when a new object will be created in memory, then the values array in this new object will by default make it of 50 size. Okay, this is my second constructor. Now the third constructor, you have already seen that new string builder and already I have passed a string here. So let's say I have passed java here. Something like this. Okay, as soon as I write this new string builder java, now what do you think? What will be the size of the values that I am going to use from inside? So its size will be 16. Plus, the size of this, which is 4. So, total is 20. So, it will make an object of 20 size. Right? So, what will happen from inside? From inside, something like this will happen. That another object will be made in our heap. Okay? The array of values inside this. Okay? What will be its size? Its size will be. Initial size is 16. Plus, to store Java, it needs 4 bytes. So, 16 plus 4 will be 20 bytes. Okay? On the previous 4 bytes, it must have stored Java. J-A-V-A. Something like this. Okay, I hope you understood this Now let's see what are the important methods in our string builder that we use So here I have listed down all the methods that are not present in our string builder and buffer Now because you know the work of string builder and buffer You have to make a string mutable so that you can change in it and you don't have to create new objects So it has all those methods that will help you in string manipulation Now you must be able to understand by its name what these methods are You can use them and see Now let's quickly do this in a code So see here I have taken a project called demo3. java So I will make an object named stringBuilder stringBuilder sb equal to let's say new stringBuilder Okay, okay And initially I will leave this empty too So you know what will happen, I will make an object named stringBuilder in heap memory And there will be 16 bytes of memory in its values array Okay Now see first of all my method is append So if I write sb.append And here I will write aditya So in my sb, in the values array, in that Aditya name will be stored. Now if I write again sb.append and here I write my name space tendon. So now my whole value will be Aditya tendon. Once you print it and see. I will write system.out.println and here I will write sb. Something like this. Now if I print it once, what do you think the answer should be? So I hope you understood append Next is our insert method And you must be understanding that if append is done in the last, insert can be inserted in the middle So I can write like this sb.insert Let's say I want to insert So I have to insert o in the second index So I wrote something like this Let's remove this So instead of 0, 1, 2, I have inserted O in the second index. Now if I print this, you know what should be printed? O has been inserted in the second index. So first A, D, now O has been inserted here. And then I, T, Y, A remained the same. I, T, Y, A hasn't changed. I haven't updated I, I have inserted it here. So you know what will happen? If my aditya is saved, A, D, I, T, Y, A, then what will O do? O will come at the place of I and I will ask it to shift to the right. So I should get ADOIDYA. So let's run it once. ADOIDYA, right? So insert does this. If you understood insert, you will also understand delete. What will delete do? It will delete an element by going to a particular index. So I can write SB.DELETE. Now it takes two overloads, start index and end index. So if I want to delete a substring, then I can write here, let's say I have to delete everything from 0 to 2. So 0, 1, 2. You know what 2 will be again. This last index is exclusive, our first index is inclusive. So as soon as I did this, now I will print my original string again. So it must have changed, right? Why? Because it changes in the original string, it doesn't make a new object. So as soon as I tried to print it, So I will see that OITY is returned. Why? Because my 0 to 2, 0, 1, 2, A, D is removed from here. Now as soon as we have delete, we have one more method SB.DELETE.CAREAT. What will it do? It will delete a character from a particular index. So if you only want to delete a character, then you can give an index. If you want to delete a substance, then you can give a delete operation. Now, apart from this, you have the method replace. Do you know what it does? Let's say we have sb.replace. It will replace another string from a particular substring. So, let's say it takes index. First index, ending index. So, what do we have to replace from 1 to 3? Let's say we have to replace xy. Something like this. So, what will it do? It will replace xy from first index to last index. Before that, let me comment on all these operations. Because there are a lot of operations. So, I don't know what's going on. Let's just keep them, sb.aditya, sb.tendon. So now my name should be aditya.tendon. I am replacing xy from 1 to 3. So 0, 1. 1, 2, 3. So instead of dit, I am saying xy should come. Now I will print my system.out.println. I will print sb. So now if I print it, then I should get axy. Look, axy. T, Y, A, Tendon. Okay. Why did it come as X, Y? You know, I said 1 to 3. And you know, our end index is exclusive. It's not included. So, I replaced it with 1 to 2. So, my first index was here. My second index was here. Instead of D, I, my X, Y came. Okay. Now obviously if there is a replace, then there is a method reverse, sb.reverse I can reverse the whole string So if I comment it, then again if I print it, then my reverse string will be printed So they have given you all the functions If you can do all these functions, then you can see that my whole reverse string has been printed Now apart from reverse, I have some other methods Like I have sb.careAt Which will tell me which character is on a particular index, you saw this in the string as well And one is setCareAt sb.setCharAt which will set a character on a particular index let's say on a third index so let's say my character is r so I can do this too we can see a character on a particular index or we can set a character on a particular index now obviously we also have length we can also use sb.length which will give us the length of this string okay, do you know what's the difference between length and capacity? let's do one thing, let's comment all these And we have a string aditya, let's comment this as well. So we have a string aditya. Now if I print the length of sb, then let's say I write system.out.println and I write sb.length. So what do you think, what should be printed? The answer should be 6 because it has 6 characters. So let's do that once and see. Absolutely, 6 has come. But I have another method which means capacity. Now I told you what does capacity tell us? Capacity tells us the size of the array inside it And initially the size of the array is 16 So when I made a new string builder here, it must have taken an array of 16 sets Now Aditya is obviously consuming only 6 blocks in it Rest of my 10 blocks are still empty So let's see what will be my capacity? That will be 16, right? Now you imagine 16 capacity came I have appended here Let's say tundun T-A-N-D-O-N. Okay. So, I have appended 6 more digits. So, 6 plus 6 is 12. Okay. The capacity should still be 16. Because, till now, I am going inside the capacity. Right. It is still 16. But, you can imagine. Now, if I append something again. S-B dot append. Now if I write anything here, here I have consumed 6 plus 6, 12 places in Aditya Tandem. And I have 4 places left out of 16. So let's say 13, 14, 15, 16. So I have consumed 4 places more. So will my capacity still come to 16? Because till now my array is full But as soon as I consume one more place My array will be dynamically bigger from inside And do you know how big it will be? 16x2 plus 2 So mine will be of size 34 It increased the size of its array So you understood what capacity does Apart from this we have one more method SB.ensureCapacity Let's say 100 So ensureCapacity says Let's say I say in string builder that I want 100 capacity So if you have already told it, then it will make the first 100 size of your array. So if I don't write the install capacity first. Now I am printing sb.capacity and I have passed 100 in string builder. So as soon as I print it, my capacity will be 100. Because I have already told it to make at least 100 size of array. But suppose I couldn't give it here for some reason. I couldn't give it here So it will use 16 capacity by default And as soon as I fill 16 It will double it So it became 34 It will double plus 2 Ensure capacity tells me That I am telling it later That my minimum capacity should be 100 So as soon as I do ensure capacity After ensuring capacity, what will be the capacity of my area size? Now if I print capacity again, then it will be minimum 100. So you can see that first it was 34, then it jumped directly to 100. So if I could not give it in the constructor in any way, then I can call ensure capacity later and tell its minimum capacity. Now I have another function, sb.trimToSize. TrimToSize TrimToSize removes all my unused memory See, what is written in manage string builder? Ensure capacity 100 Let's remove this too Let's comment this too And you can assume that I haven't written anything here as well. So, my first capacity will be 16. I added Aditya plus Tandon. So, 6 plus 6 is 12. That means 4 places were empty. Then I filled 5 places. So, as soon as I filled 5 places, how many total places did I fill? So, total place I filled, let's say 6 plus 6 plus 5. Sorry, 6 plus 6 plus 5. In a way, how many total places did I fill? I filled 17 places. I have consumed 17 places here But if you look carefully Whenever I called sb.capacity Then 34 would have been printed here As soon as I moved forward from 16 places It doubled my array But now my work is over I don't want to store anything else in this string So I will call. trimToSize So I am saying The space allocated for my 34 is useless Bring it back to how many spaces? Bring it back to 17 Because my string is in 17 Bring it back to 17 So now if I will print my capacity again, after this happens, then see what will happen to me. So see, first my print was 34, now it is 17. Because I knew that my work is complete, now I don't have to append anything else in it. So trimToSize says that bring the capacity back to the same size as my array is coming. There is no point in consuming this extra memory. So our trimToSize works there. I hope you have understood all the methods very well. There is one interesting thing in this. Some of the methods in string are available in StringBuilder and StringBuffer. But all the methods are not available in StringBuilder and StringBuffer. This means that you can never say that your StringBuilder is a superset of String class. It is not a superset. It doesn't mean that whatever is in String, it will be in StringBuilder. This is not true at all. If this would have happened, then our string builder and buffer would have become very slow. Right? Because we would have to overload a lot of methods. Now there is no need for those methods here. Why? Because at the end of the day, if you want to manipulate the string, then only you will make a string builder. Otherwise, your work was going on with a normal string. Right? Okay. We haven't seen one thing yet. If I have an object of a string builder, sb, and I want to put it back in the string, then which method do I have? Obviously, I have the same method which we have been using till now which is. toString. And do you know where this method comes from? It comes from our object class. So, imagine that I have an object called sb equal to newStringBuilder. And there are some values in it. Let's say I have done sb.append. But now I want to convert it back to string So I can write string s equal to sb dot toString Something like this And my s will be converted to string You must have seen that when I was writing system.out.println with sb My output was being printed but sb is my string builder How is output being printed directly? Because you know that system.out.println puts toString on whatever is written inside We have talked about this many times. That's why it was working there. Okay. Now look, we have seen all the transformation methods or comparison methods in string. Transformation or comparison. Okay. In which? In strings. In strings. All those don't come in string builder. So all those methods are not present in string builder. Now here a very important interview question is made. And that is equals. Equals. See, the question is that our string builder or string buffer does not overwrite this equals. So if it doesn't overwrite it, then we have two string builders. Let's say one is our sb1 equal to new string builder. New string builder. And let's say a value is added in it, aditya. And again we have one more, new string builder and in this also a value is added, aditya. In that case, if I write sb1. equals sb2, then if we expect that because equals will be overrided and it will compare the values, then the answer will be true, then we will be wrong because string builder does not override equals. What will it do by default? It will compare references. So, in this case, their references are different. So, our answer will be false. Because SB1 is pointing to a different object. SB2 is pointing to a different object. Okay. So, this is a very important interview question. So, string builder, string buffer does not override our equals method. Okay. I hope you have understood all this about string builder. Now, what role does our string buffer play? String buffer. Okay. So I told you, when do we use StringBuilder? When we need mutability in the string and StringBuilder is also fast. The work of StringBuffer is that if you need mutability, means you can change the string, don't create new object again and again, plus you also need thread safety, In that case, you will use your StringBuffer. Rest, StringBuffer has all those methods which were in our StringBuilder. All those constructors which were in our StringBuilder. The only difference is that all its methods are ThreadSafe. What does ThreadSafe mean? Again, we will read that in detail in MultiThreading. But for now, if you have a little idea of Threading, then let's say we have multiple threads. Thread1 and Thread2. And let's say I already have an object of StringBuilder. Which you know is not ThreadSafe. StringBuilder sb is equal to new StringBuilder and here I have present hello something like this and I am saying that both my threads Thread 1 wants to execute a code, what does it want to do? sb.append let's say a so it wants to append a in front of hello and our thread 2 wants to do sb.append b something like this So now imagine that I am expecting that first of all, our thread 1 enters our critical section. So our string becomes hello and then comes a. After that thread 2 enters. So our string becomes hello a and then b. Something like this. This is my expected output. But do you know what happens in the case of threading? It is possible that thread 2 enters before me and then thread 1 enters. What will happen in that case? My hello b will come first and then hello ba will come. Something like this. And this is the wrong output. I was not expecting this. This is called race condition which can happen in case of multi threading And string buffer avoids this race condition How it avoids? All the methods of string builder like append, insert, etc All the methods synchronize them Now what is synchronized and how to do it? We will study all this in depth in multi-threading lectures. Now maybe some of you may not have any idea about threading and basic. That's why we will start with scratch in multi-threading. But for now you just understand that string buffer thread is safe. But it has all the methods that are in string builder. Now because this thread is safe. So it will have an overhead of threading. Now it will have to do a lot of different things. Like it will put some locks, unlock etc. In that case you just remember. That our string builder. is very fast with string buffer. Why? Because to make thread safe, we have to do a lot of overheads. So is string builder better or faster? Faster. With string buffer. Now look, in real world programming, 90% of the time we use string builder. Maybe we can use string buffer only 10% of the time. But why? In real world, we have multithreading. So, why we are not using string buffer? Because, we told you that string builder has a big overhead. And because of that overhead, string buffer becomes very slow. We don't want our run in slow production code. So what we do is we use normal string builder. And in today's application, we don't rely on string buffer that it will use synchronized block to avoid raise condition. We avoid raise condition ourselves using locks. We put our own locks on critical section. You will understand that in multi-threading. So our string builder also works. And again if we don't need string builder, then we use normal string. StringBuilder is immutable by default and it does not have a race condition on it. StringBuilder is used very rarely in production. You must have got a good idea of what StringBuilder and StringBuffer are. You practice with these questions. Okay. Explore all these overload methods. Again, you don't need to remember anything. You just need to know what operations we can do. And if you don't know, you will write a dot in your ID. You will get a list of all the methods. I hope you enjoyed it. That's all in this video. See you in the next video. Till then, thank you so much.
