[F-lab 모각코 챌린지 27일차] TIL

JeongheeKim·2023년 6월 27일

TIL

목록 보기
27/66

String

❓new로 선언했을때와 “”로 선언했을때의 차이점

String을 선언하는 방식에는 2가지가 있다. new 키워드를 통한 객체 생성방식과 리터럴 방식이다.

  1. 리터럴 방식
    • 형식) String s1 = "HelloWorld";
    • 리터럴 방식으로 선언 시 String Constant Pool에 해당 값이 존재하는지 확인 후 이미 존재할 경우, 미리 선언된 객체를 참조한다.
  2. 일반 객체 생성 방식
    • 형식) String s4 = new String("Greeting");
    • 이 경우는 String Constant Pool과 상관없이 새로운 객체가 생성된다.
public class ProfilePrint {
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		String s2 = "HelloWorld";
		String s3 = "Greeting";
		String s4 = new String("Greeting");

		System.out.println(s1 == s2);//true
		System.out.println(s3 == s4);//false
	}
}

위의 코드를 보면 ==연산자를 통해 리터럴 방식과 일반 객체 생성 방식에서 다른 주소값을 가르키는것을 확인 할 수 있다.

Constant Pool을 사용하는 이유

자바는 메모리 오버헤드를 줄이기 위해위와 constant pool과 같은 방식을 사용한다.

  • memory overhead란?
    • 작업을 하기위해 부가적으로 소요되는 처리 시간
    • 예) CS에서 A라는 작업을 하기 위해 필요한시간이 10초 + 부가적인 처리 B까지할 경우 5초가 더 걸린다면 추가적인 5초에 대해 오버헤드라고 한다.

❓Constant Pool에서 문자열을 찾아오는 방식

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the [equals(Object)](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equals-java.lang.Object-) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and ts.intern() == t.intern() is true if and only if s.equals(t) is true.

오라클 공식 문서에 의하면 intern()는 String constant pool에 해당 String값을 equals()로 비교하여 존재하면 pool에 있는 참조값을 가져오고, 없는 경우 pool에 새로 생성하고 새로 생성된 객체의 참조값을 리턴하게 된다.

public class ProfilePrint {
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		String s2 = "HelloWorld";
		String s3 = "Greeting";
		String s4 = new String("Greeting");
		String s5 = s1.intern();

		System.out.println(s1 == s2);//true
		System.out.println(s3 == s4);//false
		System.out.println(s1 == s5);//true
	}
}
  • intern() 사용을 권장하지 않는 이유
    • 만약 새로운 문자열을 계속 만드는 프로그램에서 pool에 할당하고자 intern()메소드를 계속 호출한다면, pool이 가지는 메모리 영역은 한계가 있다. 또한, 메모리 청소를 위해 GC작업으로 인해 성능에도 영향이 갈 수 있다.

  • @Override 어노테이션의 용도는 무엇인가요?

  • 해당 메소드가 부모클래스에 있는 메소드를 재정의 선언

  • @SupressWarnings 어노테이션의 용도는 무엇인가요?
    - 경고제외

  • @Deprecated 어노테이션의 용도는 무엇인가요?
    - 더 이상 사용되지 않음을 컴파일러에게 알려준다.

  • 어노테이션을 선언할 때 사용하는 어노테이션을 무엇이라고 부르나요?
    - 메타 어노테이션

  • 4번 문제의 답에 있는 어노테이션들을 사용할 때 import 해야 하는 패키지는 무엇인가요?
    - java.lang.annotation

  • @Target 어노테이션의 용도는 무엇인가요?
    - 어노테이션이 적용될 타입을 설정한다.

  • @Retention 어노테이션의 용도는 무엇인가요?
    - 어노테이션이 적용되서 유지되는 기간을 설정한다.

  • @Inherited 어노테이션의 용도는 무엇인가요?
    - 자식클래스에서 부모클래스에 선언된 어노테이션을 상속받을 수 있다.

  • 어노테이션을 선언할 때에는 class 대신 어떤 예약어를 사용해야 하나요?
    - @Interface

0개의 댓글