What is String Buffer:
- StringBuffer is a mutable and thread-safe class used to modify strings.
- String Buffer is a child of the CharSequence interface
- StringBuffer is a **mutable class **in Java. When we perform operations like append or modify, it updates the same object instead of creating a new one, which improves performance.
- StringBuffer is synchronised/THREAD-SAFE (Multiple threads can't access it simultaneously)
How to create a StringBuffer Object:
- By using only new Keyword
StringBuffer s= new StringBuffer("Java");
Object will be created in heap memory, and the reference variable is pointing to it.
StringBuffer Methods:
- append() → Add data Adds text at the end
StringBuffer sb = new StringBuffer("Java");
sb.append(" World");
System.out.println(sb);
O/P:Java World
- insert() → Insert at specific position Adds text at a given index
StringBuffer sb = new StringBuffer("Java");
sb.insert(2, "XX");
System.out.println(sb);
o/P: JaXXva
- replace() → Replace part of string Replaces characters between indexes
StringBuffer sb = new StringBuffer("Java");
sb.replace(1, 3, "XX");
System.out.println(sb);
O/P: JXXa
- delete() → Delete characters Removes characters between indexes
StringBuffer sb = new StringBuffer("Java");
sb.delete(1, 3);
System.out.println(sb);
O/P: Ja
- reverse() → Reverse the string
StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
O/P: avaJ
- capacity() → Check memory capacity Default capacity = 16 + string length
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity());
O/P: 20
- length() → Length of string
System.out.println(sb.length());
- charAt() → Get character
System.out.println(sb.charAt(1));
- setCharAt() → Change character
StringBuffer sb = new StringBuffer("Java");
sb.setCharAt(0, 'M');
System.out.println(sb);
O/P: Mava
- ensureCapacity() → Increase capacity
sb.ensureCapacity(50);
Ensures buffer can hold at least 50 characters
What is StringBuilder:
- String Builder is a child of the CharSequence interface
- String Builder is a MUTABLE object
- StringBuilder is NON-Synchronised/NOT THREAD-SAFE(Multiple threads can access)
Methods are the same as StringBuffer
Top comments (0)