>  기사  >  Java  >  자바의 스트링버퍼

자바의 스트링버퍼

WBOY
WBOY원래의
2024-08-30 16:01:56548검색

오늘은 Java의 String Buffer에 대해 살펴보겠습니다. 먼저 자바에 대해 이야기해보자. Java는 객체 지향 프로그래밍 언어입니다. 이전에는 c, c++ 언어를 사용해 왔습니다. 이러한 언어에는 플랫폼 문제가 있었습니다. Java는 플랫폼 독립적인 언어입니다. 즉, Java는 Linux, MAC, Windows 등과 같은 모든 운영체제에서 실행될 수 있습니다. 이 주제에서는 Java의 StringBuffer에 대해 알아보겠습니다.

현재 전 세계적으로 거의 30억 대에 달하는 장치가 Java에서 실행되고 있습니다. 기술은 끝이 없는 것 같습니다. 일부 기능은 다음과 같습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

  • Java에는 재사용 가능한 코드가 많습니다.
  • 거대한 도서관
  • 플랫폼 독립적
  • 자동 가비지 수집.
  • 보안
  • 대규모 커뮤니티 지원

문자열 버퍼 클래스로 시작하기 전에 Java가 백그라운드에서 어떻게 작동하는지 알아야 합니다.

Java는 우리가 알고 있는 언어를 컴파일했습니다. 정확히 무엇을 의미하나요? 우리 모두는 컴퓨터가 바이너리 형태로 언어를 알고 있다는 것을 알고 있습니다. 즉, o와 1입니다. Java로 작성된 프로그램을 이해하려면 컴파일러가 필요합니다. Java 컴파일러는 다음 명령을 사용하여 이 프로그램을 바이트코드로 변환합니다.

Javac Someprogram.java

이 명령은 .class 파일을 생성합니다. 이 파일은 컴퓨터에서 실행 중입니다.

이제 우리는 Java 프로그램에서 정확히 무슨 일이 일어나는지 알았습니다.

이제 StringBuffer부터 시작해 보겠습니다.

Java의 StringBuffer란 무엇인가요?

Java에서는 문자열이 한번 생성되면 변경할 수 없습니다. 문자열에 새 값을 변경하거나 할당하려는 경우는 불가능합니다. 문자열 객체를 생성한 다음 값을 할당합니다. 여기서는 String Buffer 클래스가 등장합니다. String Buffer의 도움으로 문자열을 수정할 수 있습니다.

문자열이란 무엇인가요?

그러면 문자열이 무엇인지에 대한 당연한 질문이 떠오릅니다. 문자열은 문자들의 조합입니다.

다음 예를 보세요.

String city = new String("Mumbai");

다음과 같이 빈 문자열을 만들 수 있습니다.

String city = new String();

문자열 배열도 있습니다. 다음 예를 살펴보세요.

String myArray1 = new String[3];

위의 예에서는 세 개의 상수로 구성된 문자열 배열을 생성합니다.

Java에서 문자열 버퍼는 어떻게 작동하나요?

StringBuffer java의 도움으로 문자열이 변경 가능해졌습니다.

이 가변성은 정확히 무엇을 의미하나요? 다음 예를 살펴보세요. Java에서 문자열 변수에 값을 다시 할당하면 Java의 문자열이 불변이기 때문에 오류가 발생합니다.

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"
}
}

위 코드는 문자열이 변경 불가능하기 때문에 오류를 가져옵니다.

StringBuffer 클래스 설명

java.lang.StringBuffer 클래스는 스레드로부터 안전한 클래스입니다. 이는 여러 스레드가 동시에 액세스할 수 없음을 의미합니다. 변경 가능한 문자 순서가 있습니다.

StringBuffer 클래스는 문자열과 동일하지만 변경 가능하고 문자열은 변경할 수 없습니다. 모든 StringBuffer의 용량은 재할당 없이 16자입니다. 문자열의 시작, 중간 또는 끝 부분에 있는 문자열이나 하위 문자열에 항목을 추가할 수 있습니다. StringBuffer는 성장 가능한 클래스입니다.

StringBuffer 메서드는 순서대로 작동합니다. 이러한 방법과 작동 방식을 살펴보겠습니다.

StringBuffer 생성자:

StringBuffer r = new StringBuffer();

이렇게 하면 StringBuffer 클래스 유형의 빈 객체 r이 생성됩니다.

Java의 StringBuffer 클래스 메서드(예제 포함)

String Buffer 클래스는 이 문제를 극복할 수 있는 다양한 방법을 제공합니다.

몇 가지 방법은 다음과 같습니다.

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 메소드 StvStringBuffer 메소드 사용 보장능력() 무효 글자 제한을 설정합니다. str1.append(str2) str2를 문자열 str1에 추가합니다 str1.setCharAt(n, 'x') n번째 문자를 x로 수정 str1.setLength(n) str1의 n자 길이 str1.insert(n, str2) str1의 n번째 위치에 str2를 삽입합니다 정수 용량() 총 할당 용량을 반환합니다 정수 길이() 객체의 현재 길이를 반환합니다

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));
}
}
}

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());
}
}

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 );
}
}

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.

위 내용은 자바의 스트링버퍼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.