오늘은 자바에서 가장? 자주쓰이는 String 에 대해 알아보겠습니다.
String str1 = "dpdpwl";
String str2 = "dpdpwl";
String str3 = new String("melon");
String str4 = new String("melon");
if(str1 == str2) {
System.out.println("1,2는 같다");
}else {
System.out.println("1,2는 다르다");
}
if(str3 == str4) {
System.out.println("3,4는 같다");
}else {
System.out.println("3,4는 다르다");
}
if(str1.equals(str2)) {
System.out.println("1,2는 같다");
}else {
System.out.println("1,2는 다르다");
}
if(str3.equals(str4)) {
System.out.println("3,4는 같다");
}else {
System.out.println("3,4는 다르다");
}
결과는
==은 위치값(주소값) 비교 / .equals 는 문자열 비교로
1,2는 같은것을 참조하고 있고 3,4는 new로 인한 다른 객체를 생성하기때문에 위와같은 결과가 나옵니다!!
equals 는 문자열을 비교하기때문에 1,2,3,4 모두 같다고 나오게 됩니다.