StringBuffer Class is mutable sequence of characters.It's like String but content of String can be modified after creation.
Using StringBuffer different methods you can :
package com.anuj.io;
Using StringBuffer different methods you can :
- append String to existing String append() method
- insert String at specific index using insert() method
- reverse String using reverse() method.
- Find character position within String
- set character at Specific index
- delete character at specific index
- get subString using specific index
- delete characters within String
- find String buffer capacity
package com.anuj.io;
/** * * @author Anuj Patel */ public class StringBufferOperations { public static void main(String[] args) throws Exception { String str; try { str = ", This is the example of SringBuffer class and it's functions."; StringBuffer strbuf = new StringBuffer(); strbuf.append(str); System.out.println(strbuf); strbuf.delete(0, str.length()); //append element using StringBuffer strbuf.append("Hello"); strbuf.append("World"); //print HelloWorld System.out.println(strbuf); //insert element using Stringbuffer strbuf.insert(5, "_Java "); //print Hello_Java World System.out.println(strbuf); //reverse element using String buffer strbuf.reverse(); System.out.print("Reversed string : "); System.out.println(strbuf); //print dlroW avaJ_olleH strbuf.reverse(); System.out.println(strbuf); //print Hello_Java World //setCharAt using StringBuffer strbuf.setCharAt(5, ' '); System.out.println(strbuf); //prit Hello Java World //find character position using StringBuffer System.out.print("Character at 6th position : "); System.out.println(strbuf.charAt(6)); //print J //get substring using StringBuffer System.out.print("Substring from position 3 to 6 : "); System.out.println(strbuf.substring(3, 7)); //print lo J //deleteCharAt specific index using StringBuffer strbuf.deleteCharAt(3); System.out.println(strbuf); //print Helo java World //Find StringBuffer Capacity System.out.print("Capacity of StringBuffer object : "); System.out.println(strbuf.capacity()); //print 21 //delete characters using StringBuffer strbuf.delete(6, strbuf.length()); System.out.println(strbuf); //no anything } catch (StringIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } } }Output :
run: , This is the example of SringBuffer class and it's functions. HelloWorld Hello_Java World Reversed string : dlroW avaJ_olleH Hello_Java World Hello Java World Character at 6th position : J Substring from position 3 to 6 : lo J Helo Java World Capacity of StringBuffer object : 62 Helo J BUILD SUCCESSFUL (total time: 7 seconds)
No comments:
Post a Comment