"=="과 equals()에 대한 비교
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.IntegerTest();
test.StringTest();
}
public void StringTest(){
String str1 = "123";
String str2 = "123";
String str3 = new String("123");
String str4 = new String("123");
//==
System.out.println("str1 == str2: "+(str1==str2)); //true
System.out.println("str1 == str3: "+(str1==str3)); //false
System.out.println("str3 == str4: "+(str3==str4)); //false
//equals
System.out.println("str3.equals(str1): "+(str3.equals(str1))); //true
System.out.println("str3.equals(str4): "+(str3.equals(str4))); //true
}
public void IntegerTest(){
int a1 = 3; //int
Integer a2 = new Integer(3); //integer
Integer a3 = new Integer(3); //integer
Integer a4 = 3; // integer -128~127 new integer a4 a5
Integer a5 = 3;
int b1 = 130;
Integer b2 = new Integer(130);
Integer b3 = new Integer(130);
Integer b4 = 130; // integer -128~127 new integer a4 a5
Integer b5 = 130;
//equal()
System.out.println("equals() :");
System.out.println("a2.equals(a1): "+a2.equals(a1)); //true
System.out.println("b2.equals(b1): "+b2.equals(b1)); //true
//==
System.out.println("== :");
System.out.println("a1==a2: "+(a1==a2)); //true integer int , int int ,==
System.out.println("b1==b2: "+(b1==b2)); //true
System.out.println("a2==a3: "+(a2==a3)); //false integer ,== ,
System.out.println("b2==b3: "+(b2==b3)); //false
System.out.println("a1==a4: "+(a1==a4)); //
System.out.println("b1==b4: "+(b1==b4));
System.out.println("a4==a5: "+(a4==a5)); //true -128~127
System.out.println("b4==b5: "+(b4==b5)); //false -128~128
}
}
출력 결과
equals()테스트:a2.equals(a1):true b2.equals(b1):true==테스트:a1==a2:true b1===b2:true a2==a3:false b2===b3:false a1==a4:true a4==a5:true b4====b5:false
상기 프로그램 과 프로그램 결 과 를 통 해 알 수 있 듯 이:
"==":기본 유형 에 있어==비교 하 는 것 은 값 입 니 다.기본 유형 이 아 닌 경우,예 를 들 어 String 과 Integer 의 경우==비교 하 는 것 은 인용 이다.특히 주의해 야 할 것 은 integer 와 int 를 비교 할 때 integer 는 자동 으로 상 자 를 뜯 어 int 유형 으로 비교 하기 때문에 비교 하 는 값 입 니 다.
equals():비 기본 유형 만 사용 할 수 있 습 니 다.비교 하 는 것 은 값 입 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Access Request, Session and Application in Struts2If we want to use request, Session and application in JSP, what should we do? We can obtain Map type objects such as Req...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.