String Buffer methods in Java

Published: 21 August 2024
on channel: Engineering Unplugged
51
1

The `StringBuffer` class in Java is used to create mutable (modifiable) strings. Here are some commonly used methods with examples:

1. append(String str)
Adds the specified string to the end of the buffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World

2. insert(int offset, String str)
Inserts the string at the specified position.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb); // Output: Hello World

3. replace(int start, int end, String str)
Description: Replaces characters from `start` to `end` with the specified string.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java

4. delete(int start, int end)
Removes characters from `start` to `end`.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb); // Output: Hello

5. reverse()
Reverses the characters in the buffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH

6. capacity()
Returns the current capacity of the buffer.
Example:
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // Output: 16 (default capacity)

These methods demonstrate how `StringBuffer` can be used for efficient string manipulation.


On this page of the site you can watch the video online String Buffer methods in Java with a duration of hours minute second in good quality, which was uploaded by the user Engineering Unplugged 21 August 2024, share the link with friends and acquaintances, this video has already been watched 51 times on youtube and it was liked by 1 viewers. Enjoy your viewing!