Home > Java > javaTutorial > body text

StringBuffer in Java

WBOY
Release: 2024-08-30 16:01:56
Original
547 people have browsed it

Today we are going to see String Buffer in java. First, let’s talk about java. Java is an object-oriented programming language. Earlier, we have been using c, c++ languages. With these languages, we had platform issues. Java is a platform-independent language. That means java can run on any operating system like Linux, MAC, windows, etc. In this topic, we are going to learn about StringBuffer in Java.

Over the world, nearly 3 billion devices run on java today. Seems like never-ending technology. And some of the features are listed below.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Java has lots of reusable code.
  • A huge set of libraries
  • Platform independent
  • Automatic garbage collection.
  • Security
  • Big community support

Before starting with the string Buffer class, we must know how java works behind the scene.

Java has compiled language as we know it. What exactly it means? We all know the computer knows the language in the form of binary. i.e., o’s and 1’s. We need a compiler to understand the program which was written in java. Java compiler converts this program into bytecode with the help of the following command.

Javac Someprogram.java

This command creates the .class file. This file is running on the computer.

Now we know what exactly happens with the java program.

Now let’s start with StringBuffer.

What is StringBuffer in Java?

In java, strings, once created, cannot be altered. If we want to alter or assign a new value to the string is not possible. It creates a string object and then assigns the value. Here, the String Buffer class comes into the picture. With the help of String Buffer, we can modify the string.

What is the String?

Then an obvious question gets into your mind what a string is then? The string is a combination of characters.

Look at the following example.

String city = new String("Mumbai");
Copy after login

We can create an empty string as follows:

String city = new String();
Copy after login

We also have string Arrays. Look at the following example:

String myArray1 = new String[3];
Copy after login

The above example creates a string array of three constants.

How does String Buffer work in java?

With the help of StringBuffer java, strings are getting mutable.

What exactly does this mutability mean? Look at the following example. If we re-assign the value to the string variable in java, it throws an error because the string in java is immutable.

public class Str {
public static void main(String args[]){
//We are creating object here of StringBuffer class
StringBuffer city = new Stringbuffer("mumbai");
//let’s try to change the value of city here
City =" Delhi"
}
}
Copy after login

The above code will fetch an error because strings are immutable.

Explain StringBuffer Class

The java.lang.StringBuffer class is a thread-safe class. That means multiple threads cannot access them simultaneously. It has a mutable sequence of characters.

The StringBuffer class is the same as a string, but it is mutable, and the string is immutable. Every StringBuffer has a capacity of 16 characters without reallocation. It allows items to be added to the string or the substring at the start, middle, or end of the string. StringBuffer is a growable class.

StringBuffer methods work in order. We will see these methods and how they work.

StringBuffer Constructor:

StringBuffer r = new StringBuffer();
Copy after login

This creates an empty object r of type StringBuffer class.

Methods of StringBuffer Class in Java (including Examples)

String Buffer class provides us with different methods to overcome this problem.

Some of the methods are listed below.

StringBuffer Methods StvStringBuffer method use
void ensureCapacity() It sets the limit for the character.
str1.append(str2) It appends the str2 into string str1
str1.setCharAt(n, ‘x’) Modifies the nth character to x
str1.setLength(n) This length of str1 to the n characters
str1.insert(n, str2) This inserts str2 at the nth position in str1
Int capacity() This returns the total allocated capacity
Int length() It returns the current length of the object
StringBuffer Methods
StvStringBuffer method use
void ensureCapacity() It sets the limit for the character.
str1.append(str2) It appends the str2 into string str1
str1.setCharAt(n, ‘x’) Modifies the nth character to x
str1.setLength(n) This length of str1 to the n characters
str1.insert(n, str2) This inserts str2 at the nth position in str1
Int capacity() This returns the total allocated capacity
Int length() It returns the current length of the object

The above methods help the programmer to make the string mutable.

StringBuffer Methods in detail

Let’s look at the below program:

Save the below program with Example.java

class Example{
public static void main(String args[]){
StringBuffer abc = new StringBuffer("Hello World");
System.out.println("Welcome!!!"+ abc);
System.out.println("Total length of string is" + abc.length());
for(int i=0;i<=abc.length();i++){
int n = i+1;
System.out.println("We are using charAt function here :" + " " + n + " " + abc.charAt(i));
}
}
}
Copy after login

To run the above program, open the command prompt. Go to the location where the file is saved.

Then type the following two programs:

Javac Example.java

Java Example

ensureCapacity()

ensureCapacity() is the measure of the capacity to equal the specified minimumCapacity. That means the current capacity of StringBuffer is less than the argument of minimumCapacity so that the new internal array will get allocated with greater capacity.

class Ex2{
public static void main(String[] args)
{
StringBuffer abc = new StringBuffer();
// print string capacity
System.out.println("Before ensureCapacity the value is: "
+ "method capacity = "
+ abc.capacity());
abc.ensureCapacity(20);
System.out.println("After ensureCapacity the value is: + " method capacity = "
+ abc.capacity());
}
}
Copy after login

append() Method

append() method is used to append the value at the specified location.

The following example describes how we can append the string at the end of the existing string. This is one way to modify the string.

Example

class Ex2{
public static void main(String[] args)
{
StringBuffer abc = new StringBuffer("Welcome to the world ");
System.out.println("The string is:"  + abc );
abc.append("of java");
System.out.println("The string after appending is:"  + abc );
}
}
Copy after login

By appending a new string into the same variable, in the end, we modified the value of the string successfully.

In java, there are several predefined functions. We cannot write all the functions in a single article. But we can practice these functions one at a time. With the StringBuffer class, there are many methods to a string also.

Conclusion

StringBuffer class is used to make string mutable. This is an added advantage for us. If you are in the learning phase of java, you should learn how to play with strings. This is the initial level to start practicing programs written in java.

The above is the detailed content of StringBuffer in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!