본문 바로가기
✨ Java/클래스 (Class)

자바(JAVA) - String 클래스

by 환풍 2023. 2. 15.
728x90
자바에서는 문자열을 위한 String이라는 클래스를 별도로 제공한다.
String 클래스에는 문자열과 관련된 작업을 할 때 유용하게 사용할 수 있는 다양한 메소드가 포함되어 있다.

 

String 인스턴스는 한 번 생성되면 그 값을 읽기만 할 수 있고, 변경할 수는 없다.

이러한 객체를 자바에서는 불변 객체(immutable object)라고 한다.

즉, 자바에서 덧셈연산자를 이용하여 문자열 결합을 수행하면,

기존 문자열의 내용이 변경되는 것이 아니라 내용이 합쳐진 새로운 String 인스턴스가 생성되는 것이다.

 

 

String 클래스의 객체 생성 방법

첫번째,

1
2
String str1 = "hello java";
String str2 = "hello java";
cs

문자열이 동일하면 새로운 객체를 만들지 않고, 메모리 공간을 낭비하지 않도록 같은 데이터를 참조한다.

 

두번째,

1
2
String str3 = new String("hello java");
String str4 = new String("hello java");
cs

new 키워드가 새로운 객체를 생성한다는 명령어기 때문에 문자열이 같더라도 객체를 새로 생성해준다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class String01 {
    public static void main(String[] args) {
 
        String str1 = "hello java";
        String str2 = "hello java";
 
        String str3 = new String("hello java");
        String str4 = new String("hello java");
 
 
        if(str1 == str2)  
        {
            System.out.println(1);
        }
        if(str3 == str4)
        {
            System.out.println(2);
        }
 
}
 
cs

이 코드의 결과값은 그럼 어떻게 나올까?

숫자 비교에서 ==은 두 수가 같은 수인지를 판별하지만,

객체비교에서는 두 객체가 동일한 참조 값을 가지는지 판별한다.

따라서 str1과 str2만 if문을 만족하여 1이 출력된다.


String이 가지는 주소값에 대해서도 알아보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class String02 {
    public static void main(String[] args) {
 
        A a1= new A();
        A a2 = new A();
 
        a1.num = 10;
        a2.num = 5;
        System.out.println(a1.num);
        System.out.println(a2.num);
 
        a1= a2;  // a2의 주소값을 a1의 주소값에 넘겨라.
        System.out.println(a1.num);
 
        a1.num=10;
        a2.num = 20;
        System.out.println(a1.num); // 20이 나온다..
        // a1은 위에서 a2로 덮어씌어 졌다.
        System.out.println(a2.num); // 20
 
 
 
        // String은 다른 대부분의 참조변수와 다르게
        // imutable 변수이다.
        // imutable 변수 - 값이 저장되면 변하지 않는 변수.
        // 따라서 새로운 주소를 생성하고 그 주소로 값을 할당해준다.
        // 그럼 남게 된 주소는 자바에서는 그냥 지워준다.
        String str1 = "java";
        String str2 = "java";
 
        str2 = "c++";
        System.out.println(str1);
        System.out.println(str2);
    }
}
 
class A{
    int num;
}
 
cs

다음으로는 String 클래스에서 선언된 유용한 메소드를 몇가지 알아보았다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class String03 { 
    public static void main(String[] args) {
 
        String str1 = "coffee";
        //length() -> 문자열의 길이를 리턴.
        String str2 = "bread";
 
        System.out.println(str1.length());
 
        //concat() -> 두 문자열을 합쳐준다.
        String result1 =str1.concat(str2);
        System.out.println(result1);
 
        String str3 = "abcdefg";
 
        // 일부 문자열 추출
        String result2 = str3.substring(2);
        // 문자열 순서 2부터 쭉 출력해라. 즉 ,  0과 1 제외
        System.out.println(result2);
        String result3 = str3.substring(1,4);
        // 첫번째 index부터 네번째 index 전까지 출력.
        System.out.println(result3);
        // 문자열 순서 1부터 4전 까지 출력해라. 즉, str[1] ~ str[3] 까지이다.
 
        //숫자들을 문자열로 변경.
        String result4 = String.valueOf(10);
        
        //문자열 슬라이드
        String str4 = "ab, cd, ef";
        String result5[] = str4.split(",");
        // 단순히 str4.split(","); 를 하면 안된다.
        // ","로 자르면 문자열이 3개 나오는 배열로 받아야 하기 떄문이다.
        System.out.println(result5[2] );
 
 
        //charAt() 메소드는 해당 문자열의 특정 인덱스에 해당하는 문자를 반환.
        String str5 = "What";
        for(int i=0; i<str5.length(); i++)
        {
            System.out.print(str5.charAt(i)+ " ");
        }
    }
}
 
cs

반응형

댓글