Java StringBuffer: Mutable Strings with append, insert, replace, and reverse methods

TOPIC: StringBuffer in Java : StringBuffer is a class in Java used to create mutable (changeable) strings. Unlike the normal String class, the content of a StringBuffer object can be modified without creating a new object. This makes it more efficient when many string modifications are required. Key Characteristics Mutable: Content can be changed. Efficient: No new object created for every modification. Important Methods in StringBuffer : 1. append() Adds text to the end of the existing string. Example StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); Output Hello World Explanation: append() simply adds the new string at the end. 2. insert() Inserts a string at a specific position (index). Example Java StringBuffer sb = new StringBuffer("Hello World"); sb.insert(5, ", Java"); System.out.println(sb); Output Hello, Java World Explanation: insert(5, ", Java") adds text at index position 5. 3. replace() Replaces characters between two index positions. Example StringBuffer sb = new StringBuffer("Hello Java World"); sb.replace(6, 10, "Amazing"); System.out.println(sb); Output Hello Amazing World Explanation: Characters from index 6 to 10 are replaced with "Amazing". 4. reverse() Reverses the entire string. Example StringBuffer sb = new StringBuffer("Hello Amazing World"); sb.reverse(); System.out.println(sb); Output dlroW gnizamA olleH Explanation: The entire string is reversed. append() → Adding new words at the end insert() → Adding a word in the middle replace() → Erasing and writing a new word reverse() → Writing the whole sentence backward #java #Codegnan #StringBuffer #StringHandling My big thanks to my mentor #AnandKumarBuddarapu #SakethKallepu #UppugundlaSairam

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories