Java for Everyone... StringBuilder & StringBuffer

Java for Everyone... StringBuilder & StringBuffer

StringBuilder?objects are like?String?objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations, like the?String?class, has a?length()?method that returns the length of the character sequence in the builder.

Constructor Summary

StringBuilder()-Constructs a string builder with no characters in it and an initial capacity of 16 characters.

StringBuilder(CharSequence seq)-Constructs a string builder that contains the same characters as the specified CharSequence.

StringBuilder(int capacity)-Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

StringBuilder(String str)-Constructs a string builder initialized to the contents of the specified string.

Important Method Summary

append(char c)-Appends the string representation of the char argument to this sequence.

append(char[] str)-Appends the string representation of the char array argument to this sequence.

append(CharSequence s)-Appends the specified CharSequence to this sequence.

append(double d)-Appends the string representation of the double argument to this sequence.

append(String str)-appends the specified string to this character sequence.

appendCodePoint(int codePoint)-Appends the string representation of the codePoint argument to this sequence.

insert(int offset, char c)-Inserts the string representation of the char argument into this sequence.

replace(int start, int end, String str)-Replaces the characters in a substring of this sequence with characters in the specified String.

reverse()-Causes this character sequence to be replaced by the reverse of the sequence.

substring(int start)-Returns a new String that contains a subsequence of characters currently contained in this character sequence.

substring(int start, int end)-Returns a new String that contains a subsequence of characters currently contained in this sequence.

toString() Returns a string representing the data in this sequence.

You can follow this official website link for more details on Stringbuilder method & classes.

Examples-

  1. StringBuilder sb = new StringBuilder();//Creates an empty StringBuilder with an initial capacity of 16 characters.
  2. StringBuilder sb = new StringBuilder(int capacity);//Creates an empty StringBuilder with a specified initial capacity.
  3. StringBuilder sb = new StringBuilder(String str);//Creates a StringBuilder initialized with the contents of the given string.
  4. A basic program-

public static void main(String[] args) {
		StringBuilder sb1 = new StringBuilder("Hello ,Java");
		// Append
		sb1.append(" StringBuffer!");
		System.out.println("After append: " + sb1); // Output: Hello ,Java StringBuffer!
		// Insert
		sb1.insert(25, " Welcome");
		System.out.println("After insert: " + sb1); // Output: Hello ,Java StringBuffer! Welcome
		// Replace
		sb1.replace(12, 24, "World");
		System.out.println("After replace: " + sb1); // Output: Hello ,Java World! Welcome
		// Delete
		sb1.delete(11, 17);
		System.out.println("After delete: " + sb1); // Output: Hello ,Java! Welcome
		// Reverse
		sb1.reverse();
		System.out.println("After reverse: " + sb1); // Output: emocleW !avaJ, olleH
	}        
Key Characteristics of StringBuilder

StringBuilder is a class in Java designed for creating and manipulating mutable strings.

  • Unlike String (immutable), StringBuilder allows modifications to the string object itself without creating a new object.
  • Provides methods like append, insert, replace, delete, reverse, etc., making it versatile for string manipulation tasks.
  • StringBuilder methods are not synchronized, which makes it faster than StringBuffer.
  • The initial capacity can be specified, or it defaults to 16 characters.
  • A StringBuilder can be converted to a String using the toString() method, allowing easy integration with APIs expecting String objects.
  • Many methods return the same StringBuilder object, enabling method chaining for concise code.

Example-

public static void main(String[] args) {	
		StringBuilder sb = new StringBuilder("Hey");
		sb.append(" this").append(" Java");
		System.out.println(sb); // Output: Hey this Java
		
	}        
StringBuffer

StringBuffer is a class in Java used to create mutable (modifiable) strings. Unlike the String class, where objects are immutable (cannot be changed once created), StringBuffer objects can be modified without creating new instances.

StringBuffer is thread-safe, as its methods are synchronized, making it suitable for multi-threaded applications. However, this synchronization can make it slower compared to StringBuilder

Basic programming example-

 StringBuffer sb1 = new StringBuffer("Hello ,Java");

	        // Append
		   sb1.append(" StringBuffer!");
	       System.out.println("After append: " + sb1); // Output: Hello ,Java StringBuffer!

	        // Insert
	       sb1.insert(25, " Welcome");
	        System.out.println("After insert: " + sb1); // Output: Hello ,Java StringBuffer! Welcome
	        // Replace
	        sb1.replace(12, 24, "World");
	        System.out.println("After replace: " + sb1); // Output: Hello ,Java World! Welcome
	        // Delete
	        sb1.delete(11, 17);
	        System.out.println("After delete: " + sb1); // Output: Hello ,Java! Welcome
	        // Reverse
	        sb1.reverse();
	        System.out.println("After reverse: " + sb1); // Output: emocleW !avaJ, olleH
	    }        
Key Characteristics of StringBuffer:

Mutable Strings: Strings can be modified in place (e.g., appending, deleting, or replacing characters).

Thread-Safe: Methods of StringBuffer are synchronized, making it thread-safe for multi-threaded environments. However, this comes with a performance trade-off compared to StringBuilder.

Performance: It is faster than String when there are multiple string modifications but slower than StringBuilder due to synchronization.

Key Differences Between StringBuffer and StringBuilder in Java

StringBuffer Vs SringBuilder
StringBufferVsStringBuilder

/*

This is article is based on JDK 8, any changes on features, enhancement or deprecated options can be referred to official release notes-

https://www.oracle.com/java/technologies/javase/jdk-relnotes-index.html

https://dev.java/learn/

*/

要查看或添加评论,请登录

Arjun K.的更多文章

  • Java OOPs...Encapsulation!

    Java OOPs...Encapsulation!

    Consider a real-life example of your bank account, your account balance is private—you wouldn’t want anyone to directly…

  • Little’s Law in Performance Testing

    Little’s Law in Performance Testing

    In 1954, John Little published a paper in which he described the queueing theory by a new law. Later, it is named…

  • Performance Metrics- Throughput, latency and response time!

    Performance Metrics- Throughput, latency and response time!

    Throughput Throughput serves as a crucial performance metric for assessing system efficiency, identifying bottlenecks…

  • Application Performance Improvement using CAST SQG formerly AIP.

    Application Performance Improvement using CAST SQG formerly AIP.

    ??What is CAST Structural Quality Gate (SQG) formerly AIP ? CAST SQG draws on CAST’s extensive experience in deep…

  • Performance Test-An Overview!

    Performance Test-An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Software Performance Test - An Overview!

    Software Performance Test - An Overview!

    Performance testing is a type of software testing that focuses on how well an application performs under various…

  • Compile-time & Runtime Errors in Java..

    Compile-time & Runtime Errors in Java..

    Compile-time A compile-time error in Java refers to an error that occurs during the compilation phase, when the Java…

  • Java for Everyone...Encapsulation.

    Java for Everyone...Encapsulation.

    Consider a real-life example of your bank account. Your account balance is private—you wouldn’t want anyone to directly…

  • Java Collection Framework in Selenium

    Java Collection Framework in Selenium

    In Selenium WebDriver, Java collections play a crucial role in managing and manipulating data such as lists of web…

  • Java for Everyone... Arrays

    Java for Everyone... Arrays

    An array is a container object that holds a fixed number of values of a single type. The length of an array is…

社区洞察

其他会员也浏览了