티스토리 뷰
반응형
String 변수 생성
String str1 = "apple"; //리터럴을 이용한 방식
String str2 = "apple"; //리터럴을 이용한 방식
String str3 = new String("example"); //new 연산자를 이용한 방식
String str4 = new String("example"); //new 연산자를 이용한 방식
리터럴을 이용한 방식
string constant pool
이라는 영역에 생성intern()
메서드가 호출됨intern()
: 주어진 문자열이 string constant pool에 존재하는지 검색해서 존재하면 주소를 반환
new 연산자를 이용한 방식
Heap
영역에 생성
문자열 비교
== 연산자
- 비교하고자 하는 대상의 주소값을 비교
// 불일치
public class compare {
public static void main(String[] args) {
String s1 = "apple";
String s2 = new String("apple");
if(s1 == s2) {
System.out.println("일치");
}else {
System.out.println("불일치");
}
}
}
equals()
- 비교하고자 하는 대상의 값 자체를 비교
// 일치
public class compare {
public static void main(String[] args) {
String s1 = "apple";
String s2 = new String("apple");
if(s1.equals(s2)) {
System.out.println("일치");
}else {
System.out.println("불일치");
}
}
}
반응형
댓글