|
| 1 | +package string.stringbuffer; |
| 2 | + |
| 3 | +public class StringBufferAndBuilderExample { |
| 4 | + public static void main(String[] args) { |
| 5 | + // String buffer helps us to create string which are mutable... |
| 6 | + // it is used when we want to make changes in the existing string.. |
| 7 | + // Object creation is needed for using the stringbuffer class... |
| 8 | + |
| 9 | + StringBuffer sb = new StringBuffer("Hello "); |
| 10 | + |
| 11 | + // string buffer has three constructor... |
| 12 | + // StringBuffer sb = new StringBuffer(); --> this create empty string buffer with capacity 16. |
| 13 | + // StringBuffer sb = new StringBuffer("Hey"); --> this create string buffer with specified string. |
| 14 | + // StringBuffer sb = new StringBuffer(100); --> this create string buffer with specified capacity. |
| 15 | + |
| 16 | + // Method of StringBuffer() class... |
| 17 | + // once a method perform upon the string of string buffer class then it is modified not return a new string. |
| 18 | + |
| 19 | + // append() method... |
| 20 | + sb.append("Java"); |
| 21 | + System.out.println(sb); // Hello Java |
| 22 | + |
| 23 | + // insert() method... |
| 24 | + sb.insert(5, " World"); |
| 25 | + System.out.println(sb); // Hello World Java --> because sb is modified now |
| 26 | + |
| 27 | + // replace() method... |
| 28 | + sb.replace(2,5, " Bye"); |
| 29 | + System.out.println(sb); // He Bye World Java --> because sb is modified |
| 30 | + |
| 31 | + // delete() method... |
| 32 | + sb.delete(0,7); |
| 33 | + System.out.println(sb); // World Java |
| 34 | + |
| 35 | + // reverse() method... |
| 36 | + sb.reverse(); |
| 37 | + System.out.println(sb); // Java World |
| 38 | + sb.reverse(); |
| 39 | + System.out.println(sb); |
| 40 | + |
| 41 | + // capacity() method... |
| 42 | + sb.capacity(); |
| 43 | + System.out.println(sb.capacity()); // 22 --> default capacity is 16. |
| 44 | + |
| 45 | + // ensureCapacity() method... |
| 46 | + sb.ensureCapacity(30); |
| 47 | + System.out.println(sb.capacity()); // now (22*2)+2 = 46 --> if given capacity is greator than the original capacity |
| 48 | + sb.ensureCapacity(40); |
| 49 | + System.out.println(sb.capacity()); // now no change because given capacity is lesser than given capacity |
| 50 | + |
| 51 | + /* StringBuilder is same functionality as StringBuffer, Some difference in between them is that StringBuffer is |
| 52 | + non-synchronized and thread-safe but StringBuilder is non-synchronized and non-thread-safe. |
| 53 | + --> thread-safe is like two thread not call same stringbuffer object simultaneously |
| 54 | + --> non-thread-safe is like two thread can call same stringbuilder object simultaneously */ |
| 55 | + |
| 56 | + // ALL FUCNTIONALITY AND METHOD WORKING ARE SAME FOR BOTH STRINGBUFFER & STRINGBUILDER. |
| 57 | + |
| 58 | + /* --> Author - Ravi Pratap Singh <-- */ |
| 59 | + } |
| 60 | +} |
0 commit comments