> Java > java지도 시간 > 본문

Java의 문자열 클래스

WBOY
풀어 주다: 2024-08-30 15:42:54
원래의
232명이 탐색했습니다.

문자열은 java.lang을 확장하는 Java의 최종 클래스입니다. 문자열로 표현되는 객체입니다. Serialized, Comparable 및 CharSequence 인터페이스는 문자열 클래스로 구현됩니다. "string example"과 같은 모든 문자열 리터럴은 String 클래스의 인스턴스로 처리됩니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

문자열 작업

  • 이런 문자열을 원할 경우: 저는 뭄바이의 "궁전"에 있습니다.
  • 이런 경우 자바 컴파일러는 “나는 뭄바이의 “Palace”에 있습니다.”라고 오해하여 오류를 발생시킵니다.
  • 컴파일러에게 모호한 상황이 발생합니다.
  • 이러한 상황에 대처하기 위해 백슬래시 '' 문자가 도움이 될 것입니다.

코드:

public class test
{
public static void main(String[] args)
{
String s1 = "I am at a \"Palace \" of Mumbai.";
System.out.println(s1);
}
}
로그인 후 복사

출력:

Java의 문자열 클래스

예제 #1: 두 개의 문자열 추가

두 개의 문자열을 추가하면 결과는 문자열 연결이 됩니다.

코드:

public class test
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
int c = a+b;
System.out.println(c);
String s = "10";
int d = 10;
String s1 = s+d;
System.out.println(s1);
}
}
로그인 후 복사

출력:

Java의 문자열 클래스

예 #2: 문자열은 변경할 수 없습니다.

문자열은 한번 생성되면 그 값을 변경할 수 없습니다. 문자열은 일정합니다. 이러한 속성은 불변 속성으로 알려져 있습니다.

코드:

class Test
{
public static void main(String args[])
{
String str="I am string";
str.concat(" I am instance of String class.");
System.out.println(str);
}
}
로그인 후 복사

출력:

Java의 문자열 클래스

설명:

  • 먼저 "I am string"으로 문자열 str을 생성했습니다. 그런 다음 문자열 연결 방법을 사용하여 일부 문자열을 연결합니다.
  • 그러나 문자열은 불변이므로 값이나 상태를 변경할 수 없습니다. 연결된 문자열은 메모리의 또 다른 부분을 차지하게 됩니다.
  • 참조 str은 여전히 ​​"I am string"을 나타냅니다.
  • 동일한 문자열 값을 업데이트하려면 다음 예와 같이 연결된 문자열을 특정 참조에 할당해야 합니다.

예시 #3

코드:

class Test
{
public static void main(String args[])
{
String str="I am string";
str = str.concat(" I am instance of String class.");
System.out.println(str);
}
}
로그인 후 복사

출력:

Java의 문자열 클래스

변경 가능한 문자열을 생성하려면 StringBuffer 또는 StringBuilder 클래스를 사용할 수 있습니다.

문자열 클래스 유형

Java에는 두 가지 유형의 문자 시퀀스 클래스가 있습니다. 불변 클래스인 String 클래스와 가변 클래스인 StringBuilder, StringBuffer.

StringBuilder와 StringBuffer에는 몇 가지 차이점이 있습니다.

  • StringBuffer는 스레드로부터 안전하고 동기화됩니다. 이는 두 스레드가 동시에 문자열 버퍼의 메서드에 액세스할 수 없음을 의미합니다.
  • StringBuilder는 동기화되지 않으며 스레드로부터 안전하지 않습니다. 이는 두 스레드가 문자열 버퍼의 메서드에 동시에 액세스할 수 있음을 의미합니다.
  • 효율성 측면에서는 StringBuilder가 StringBuffer보다 더 효율적입니다.

아래는 StringBuffer와 StringBuilder의 예입니다

1. 스트링버퍼

코드:

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer bufferstring=new StringBuffer("I am stringbuffer.");
bufferstring.append("I am thread safe.");
System.out.println(bufferstring);
}
}
로그인 후 복사

출력:

Java의 문자열 클래스

2. 스트링빌더

코드: 

class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder builderstring=new StringBuilder("I am stringbuilder.");
builderstring.append("I am more efficient than string buffer.");
System.out.println(builderstring);
}
로그인 후 복사

출력:

Java의 문자열 클래스

Java에서 문자열 클래스는 어떻게 작동하나요?

Java에서 문자열은 문자의 시퀀스이며 c,c++와 달리 String 클래스의 객체입니다.

이 클래스에서 지원하는 생성자는 다음과 같습니다.

Java의 중요한 문자열 생성자

아래에는 Java의 몇 가지 중요한 문자열 생성자가 나와 있습니다.

  • String(): 빈 데이터로 문자열 객체를 초기화합니다.
  • String(byte[] bytes): 바이트 배열을 디코딩하고 생성된 참조에 할당하여 문자열을 구성합니다.
  • String(char[] value): 제공된 문자 배열로 문자열을 구성하고 생성된 참조에 할당합니다.

Java의 중요한 문자열 메서드

아래에는 Java의 몇 가지 중요한 문자열 메소드가 나와 있습니다.

  • charAt(int index): It returns the character present at the given index in a string.
  •  concat(String s): It concatenates the existing string with the string provided as an argument.
  • equals(Object anObject): Compares this string to the given object and return boolean.
  • substring(int beginIndex, int endIndex): It returns a string, i.e. substring of this string.
  • toLowerCase(): Converts a string to lower case.
  • toUpperCase(): Converts a string to upper case.
  • startsWith(String prefix): Tests if the string starts with the prefix provided as an argument.
  • trim(): It trims all leading and trailing whitespaces from the string.

Examples of String Class in Java

Given below are the examples of String Class in Java:

Example #1

Let us check whether the string contains only whitespaces.

Code:

class StringWhitespaceChecker
{
public static boolean isStringWithWhitespace(String s)
{
if(s.trim().isEmpty)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
StringWhitespaceChecker s1 = new StringWhitespaceChecker();
String s =new String(" ");
String string = new String(" I am string. ");
boolean condition1 = s1.isStringWithWhitespace(s);
boolean condition2 = s1.isStringWithWhitespace(string);
System.out.println(condition1);
System.out.println(condition2);
}
}
로그인 후 복사

Output:

Java의 문자열 클래스

Explaination:

  • The function first trims all the whitespaces and then checks whether it is empty; if it is so, it will return true or false, respectively.

Example #2

String function.

Code:

class Test
{
public static void main(String args[])
{
String s = new String("hello");
s.toUpperCase();
System.out.println(s);
s = s.concat("world");
System.out.println(s);
System.out.println(s.charAt(1));
String s1 = new String("helllo");
boolean b = s.equals(s1);
System.out.println(b);
}
}
로그인 후 복사

Output:

Java의 문자열 클래스

Example #3

Java String to toCharArray()

Code:

class Test
{
public static void main(String args[])
{
String s = new String("hello");
Char[] c1 = s.toCharArray()
for(int i=0;i<c1.length;i++)
{
System.out.println(c1[i]);
}
}
}
로그인 후 복사

Output:

Java의 문자열 클래스

Conclusion

This article is focused upon the criteria such as introduction to the string, String constructors, String Methods, Types of String classes, String immutable, StringBuffer and StringBuilder. Examples of each property. A string is a very important class in Java. You will work with string manipulation in multiple ways in real-world projects.

위 내용은 Java의 문자열 클래스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!