String을 선언하는 방식에는 2가지가 있다. new 키워드를 통한 객체 생성방식과 리터럴 방식이다.
String s1 = "HelloWorld";String s4 = new String("Greeting");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과 같은 방식을 사용한다.
When the intern method is invoked, if the pool already contains a string equal to this
Stringobject 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, thisStringobject is added to the pool and a reference to thisStringobject is returned.It follows that for any two strings
sandt,s.intern() == t.intern()istrueif and only ifs.equals(t)istrue.
오라클 공식 문서에 의하면 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
}
}
@Override 어노테이션의 용도는 무엇인가요?
해당 메소드가 부모클래스에 있는 메소드를 재정의 선언
@SupressWarnings 어노테이션의 용도는 무엇인가요?
- 경고제외
@Deprecated 어노테이션의 용도는 무엇인가요?
- 더 이상 사용되지 않음을 컴파일러에게 알려준다.
어노테이션을 선언할 때 사용하는 어노테이션을 무엇이라고 부르나요?
- 메타 어노테이션
4번 문제의 답에 있는 어노테이션들을 사용할 때 import 해야 하는 패키지는 무엇인가요?
- java.lang.annotation
@Target 어노테이션의 용도는 무엇인가요?
- 어노테이션이 적용될 타입을 설정한다.
@Retention 어노테이션의 용도는 무엇인가요?
- 어노테이션이 적용되서 유지되는 기간을 설정한다.
@Inherited 어노테이션의 용도는 무엇인가요?
- 자식클래스에서 부모클래스에 선언된 어노테이션을 상속받을 수 있다.
어노테이션을 선언할 때에는 class 대신 어떤 예약어를 사용해야 하나요?
- @Interface