Day 23 (23.01.27)

Jane·2023년 1월 27일
0

IT 수업 정리

목록 보기
23/124

1. 생성자 오버로딩과 this 사용

class Person {
	private int regiNum;  // 주민등록번호
	private int passNum; // 여권번호
	
	Person(){
		regiNum = 0;
		passNum = 0;
	}
	
	Person(int regiNum, int passNum){
		this.regiNum = regiNum;
		this.passNum = passNum;
	}
	
	Person(int rnum){
		this(rnum, 0);
	}
 }   
  • 생성자 안에서 자신을 호출할 때는 this(); 를 사용한다.
    (자신의 이름을 직접 부르는 행위는 오류가 뜬다!)

2. String 클래스

2-1. 문자열을 생성하는 방법

  • 클래스는 일반적인 객체처럼 생성한다. String도 그렇다.
  • String 클래스는 Java에서 지정된 방식으로 코딩할 수 있다.
    (" " 안에 문자열을 넣는 방식으로 할 수 있다.)
  • " " 안의 문자들은 static으로 처리된다.
String str1 = new String("Simple String");
String str2 = "The Best String";

2-2. 문자열 생성 방법의 차이점

  • str3, str4 new String("Simple String");
    : 객체를 생성할 때 할당받는 주소값이 다르다
  • str1, str2 "Simple String";
    : String 안에 있는 static 기능으로 인해 같은 값을 공유하게 된다.
    (내용 안에 대-소문자 혹은 스페이스 등 문자열이 조금이라도 다르면 다른 번지에 static으로 올려버린다.)
public 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("같은 인스턴스 참조");
		} else {
			System.out.println("다른 인스턴스 참조");
		}

		if (str3 == str4) {
			System.out.println("같은 인스턴스 참조");
		} else {
			System.out.println("다른 인스턴스 참조");
		}
	}

}

[Console]
같은 인스턴스 참조
다른 인스턴스 참조

  • String의 불변성 : 한번 생성한 객체 안의 값을 두번 다시 바꾸지 못하게 된다.
    (데이터 멤버가 final로 선언되어 있다.)
  • String 연산의 결과값은 다른 곳에 만들어주고 return해준다.
private final byte[] value;

2-3. String - switch 사용

  • 정수가 오는 부분에 String을 사용할 수 있다.
    (int 자리에 숫자가 아닌 주소값을 메모리에 올려서 돌리게 된다.)
public class JavaPractice {

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

}

3. String 클래스 안의 여러 가지 함수들

3-1. 문자열 비교하기 (equals)

  • 주소값 비교가 아닌, 함수를 이용하여 문자열을 비교한다.
  • str1 == str3 처럼 주소값이 같은지 비교하지 않도록 한다.

public class JavaPractice {

	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.equals(str3)) {
			System.out.println("같은 문자열");
		}else {
			System.out.println("다른 문자열");
		}
	}
}

[Console]
같은 문자열


String 클래스 > equals 함수 (boolean)

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (coder() == aString.coder()) {
                return isLatin1() ? StringLatin1.equals(value, aString.value)
                                  : StringUTF16.equals(value, aString.value);
            }
        }
        return false;
    }

3-2. concat (문자열 이어붙이기)

public class StringConcat {

	public static void main(String[] args) {
		String str1 = "Coffee";
		String str2 = "Bread";
		
		String str3 = str1.concat(str2);
		System.out.println(str3);
		
		String str4 = "Fresh".concat(str3);
		System.out.println(str4);
	}

}

[Console]
CoffeeBread
FreshCoffeeBread


String 클래스 > concat 함수 (String)

    public String concat(String str) {
        if (str.isEmpty()) {
            return this;
        }
        if (coder() == str.coder()) {
            byte[] val = this.value;
            byte[] oval = str.value;
            int len = val.length + oval.length;
            byte[] buf = Arrays.copyOf(val, len);
            System.arraycopy(oval, 0, buf, val.length, oval.length);
            return new String(buf, coder);
        }
        int len = length();
        int olen = str.length();
        byte[] buf = StringUTF16.newBytesFor(len + olen);
        getBytes(buf, 0, UTF16);
        str.getBytes(buf, len, UTF16);
        return new String(buf, UTF16);
    }

3-3. length

  • String의 길이를 구하는 함수

String 클래스 > length 함수 (int)

public int length() {
   return value.length >> coder();
}

3-4. charAt

  • String의 문자 인덱스 위치를 출력하는 함수 (0부터 시작)

String 클래스 > charAt 함수 (char, 매개변수는 int)

public char charAt(int index) {
   if (isLatin1()) {
      return StringLatin1.charAt(value, index);
   } else {
     return StringUTF16.charAt(value, index);
   }
}

4. length와 charAt을 이용하여 문자열 뒤집기

4-1. 문자열 그대로 출력하는 코드

public static void main(String[] args) {
	String str = "abcde";
		
	for(int i=0; i<str.length(); i++) {
		System.out.print(str.charAt(i));
	}
}

[Console]
abcde

4-2. 문자열을 뒤집어서 출력하는 코드

public static void main(String[] args) {
	String str = "abcde";

	for (int i = str.length() - 1; i >= 0; i--) {
		System.out.print(str.charAt(i));
	}
}

[Console]
edcba

profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글