제이제이
article thumbnail

 

String 클래스


  • 지금까지 String 클래스는 단순히 문자열을 입력하고 사용하는 것으로만 알고 있었습니다.
  • 이번시간에는 String클래스에 대해 자세히 살펴보고 정리하겠습니다.

 

String 클래스의 인스턴스 생성

방법 1)

String str = new String("간단한 문자열 표현");

 

  • 문자열 표현을 위한 String 인스턴스의 생성방법은 다음과 같습니다. 일반적으로 그동안 객체를 생성했던 방법과 차이가 없습니다.
System.out.println(str);

 

📸 출력 결과

간단한 문자열 표현

 

  • 지금까지 많이 사용했던 System.out.println메소드 내부에는 다음과 같이 정의되어 있기 때문에 String 객체의 참조값을 인자로 전달하는 것이 가능했습니다.
public void println(String s) {...}

 

방법2)

  • 다음과 같은 방법으로도 String 인스턴스를 생성할 수 있습니다.
  • 보통 new를 이용한 String형 인스턴스 사용보다 이 방법을 자주 사용합니다.
String str = "간단한 문자열 표현";

 

  • 이와 관련하여 다음의 코드를 살펴봅시다.

💻 예제 코드

public class StringInst {
    public static void showString(String str){
        System.out.println(str);
        System.out.println(str.length());
    }

    public static void main(String[]args){
        String str1 = new String("Simple String");
        String str2 = "The Best String";

        System.out.println(str1);
        System.out.println(str1.length()); // length의 반환 값을 인자로 전달
        System.out.println();

        System.out.println(str2);
        System.out.println(str2.length());
        System.out.println();

        showString("Funny String");
    }
}

 

📸 출력 결과

Simple String
13

The Best String
15

Funny String
12

 

  • 위의 코드에서 주목해야 할 점은 다음과 같습니다.
  • String 형 객체를 두가지 방법을 이용하여 생성을 사용하였습니다.
String str1 = new String("Simple String");
String str2 = "The Best String";
  • String 클래스에 정의된 length 메소드를 호출하여 문자열의 길이를 반환하고 이를 출력하였습니다.
  • 그리고 String 클래스에 다음과 같이 정의된 length 메소드를 호출하여 문자열의 길이를 반환하고 이를 출력하였습니다.

 

String 클래스의 length메소드

public int length() {....} //문자열 길이를 정수로 반환한다.

 

❓ 메소드 length의 반환값을 어떻게 메소드가 인자로 인식할 수 있었을까?

🔜  println의 메소드는 다음과 같이 오버로딩이 되어 있기 때문에 length의 반환값을 인자로 인식할 수 있습니다.

void println() {....}
void println(int x) (...}
void println(String x) {....}

 

showString(”Funny String”)의 출력 과정

  • 메소드 호출문 showString(“Funny String”)에서는 인스턴스 생성되어 참조값이 전달됩니다.
showString("Funny String"); 
-> showString(0x1234); //0x1234는 인스턴스의 참조 값이라 가정

 

   1. 위의 문장의 showString 메소드가 호출하게 되면 “Funny String”을 대상으로 인스턴스(객체)가 생성되고
     String 인스턴스(객체)의 참조 값이 전달되게 됩니다.

   2. 그리고 나서 이 인스턴스(객체)의 참조 값이 문자열을 대신하게 됩니다.

   3. 매개변수 선언이 String형으로 선언되어 있는 메소드(showString)를 통해 문자열의 참조 값을 전달받습니다.

public static void showString(String str) {....}

   

  4. showString메소드를 실행합니다.

    public static void showString(String str){
        System.out.println(str);
        System.out.println(str.length());
    }

 

❓ 문자열 정보를 가지고 있는 인스턴스(객체)를 생성하는 두 가지 방법의 차이점은 있을까?

  • 두가지 방법의 차이를 알아보기 위해 다음의 코드를 살펴봅시다.

 

💻 예제 코드

class ImmutableString{
	public static void main(String[] args){
			String str1 = "simple String";
			String str2 = "simple String";
		
			String str3 = new String("Simple String");
			String str4 = new String("Simple String");

			if(str1 == str2){
            System.out.println("str1과 str2는 동일 인스턴스 참조");
        }else {
            System.out.println("str1과 str2는 다른 인스턴스 참조");
        }

        if(str3 == str4){
            System.out.println("str3과 str4는 동일 인스턴스 참조");
        }else {
            System.out.println("str3과 str4는 다른 인스턴스 참조");
        }
    }
}

 

📸 출력 결과

str1과 str2는 동일 인스턴스 참조
str3과 str4는 다른 인스턴스 참조

 

  • 참조변수를 대상으로 한 ==연산은 “참조변수의 참조 값”에 대해 비교 연산을 합니다.
  • 참조변수의 동일한 값을 가지면 true, 서로 다르면 false를 출력합니다.

 

참조변수의 참조값이 같은 경우

public static void main(String[] args){
		ZZZ inst1 = new ZZZ ();
		ZZZ inst2 = inst1; //두 참조변수는 동일 인스턴스 참조
		System.out.println(inst1 == inst2); //동일 인스턴스를 참조함으로 true 출력
}

 

참조변수의 참조값이 다른 경우

public static void main(String[] args){
		ZZZ inst1 = new ZZZ();
		ZZZ inst2 = new ZZZ();
		System.out.println(inst1 == inst2); //다른 인스턴스를 참조함으로 false 출력
}

 

  • 위의 코드를 통해 방법2로 생성한 인스턴스는 같은 인스턴스임을 확인할 수 있습니다.
String str1 = "simple String";
String str2 = "simple String";

 

  • 다음과 같이 방법1로 생성한 인스턴스는 다른 인스턴스임을 알 수 있습니다.
String str3 = new String("Simple String");
String str4 = new String("Simple String");

 

❓ 차이가 나는 이유는?

  • String 인스턴스는 생성 후, 입력된 문자열 값을 소멸될 때까지 바꿀수 없는 Immutable 인스턴스이기 때문입니다.
  • 예를 들어 다음과 같이 String 인스턴스를 생성하면, 생성된 인스턴스 내부에 문자열 “XtoZ”를 가지게 되고 이 내용은 인스턴스(객체)가 소멸될 때까지 바꿀 수 없습니다.

 

String str = “XtoZ”

 

  • 이 때문에 내용이 같은 인스턴스를 다음과 같이 생성하게 하면 문자열 내용이 같기 때문에 맨 하단과 같이 하나의 인스턴스를 생성해서 이를 공유하는 방식으로 코드를 작성합니다.

 

String str1 = "XtoZ";
String str2 = "XtoZ";

 

변경

Stirng str1 = "XtoZ";
String str2 = str1;

 

String 인스턴스가 갖고 있는 문자열 내용 비교

  • String인스턴스가 가지고 있는 문자열의 내용을 비교하기 위해서 equals라는 메소드를 사용합니다.

 

💻 예시 코드

public static void main(String[] args ) {
		String strl new String("XtoZ");
		String str2 = new String("XtoZ");
		
	 if(strl.equals(str2)) // 문자열 내용이 같으면 equals 메소드는 true 반환
		System.out.println("두 문자열의 내용이 같습니다. ") ;
	 else
		System.out.println("두 문자열의 내용이 다릅니다. ") ;
}

 

📸 출력결과

두 문자열의 내용이 같습니다. 

 

String 인스턴스를 이용하여 switch문을 구성

  • 자바 7부터 String 인스턴스를 이용한 switch문의 구성이 가능해졌습니다. 다음과 같이 switch문을 구성할 수 있습니다.

💻 예시 코드

public class StringSwitchTest{
public static void main(String[] args) { 
		Strring str =  "three";
    Switch(str) { 
			case "one" :
				System.out.println("one"); 
				break;
			case "two":
				System.out.println("two" );
			 break;
			case "three":
				System.out.println("three");
			 break;
			default:
				System.out.println("default");
   }
	}
}

 

📸 출력결과

three

 

📒 Reference (참고 자료)


  1. 윤성우의 열혈 자바
profile

제이제이

@아사비치즈스틱

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!