String 변수 생성시 주소할당
- 리터럴을 이용한 방식
- string constant pool이라는 영역에 존재
- String을 리터럴로 선언할 경우 내부적으로 String의 intern() 메서드가 호출되게 되고 intern() 메서드는 주어진 문자열이 string constant pool에 존재하는지 검색하고 있다면 그 주소값을 반환하고 없다면 string constant pool에 넣고 새로운 주소값을 반환
- new 연산자를 이용한 방식
주소값 비교(==)와 값 비교(equals)
- == 연산자는 비교하고자 하는 두개의 대상의 주소값을 비교
- String클래스의 equals 메소드는 비교하고자 하는 두개의 대상의 값 자체를 비교
- 기본 타입의 int형, char형등은 Call by Value 형태로 기본적으로 대상에 주소값을 가지지 않는 형태
- String은 일반적인 타입이 아니라 클래스
- 클래스는 기본적으로 Call by Reference형태로 생성 시 주소값이 부여
==연산자
public class compare {
public static void main(String[] args) {
String s1 = "abcd";
String s2 = new String("abcd");
if(s1 == s2) {
System.out.println("같다");
}else {
System.out.println("틀리다");
}
}
}
equals()
public class compare {
public static void main(String[] args) {
String s1 = "abcd";
String s2 = new String("abcd");
if(s1.equals(s2)) {
System.out.println("같다");
}else {
System.out.println("틀리다");
}
}
}