티스토리 뷰

Given:

public class Product{
int id;
String name;
public Product(int id, String name){
this.id=id;
this.name=name;
}
}

public class Class47 {
public static void main(String[] args) {
Product p1=new Product(101,"Pen");
Product p2=new Product(101,"Pen");
Product p3=p1;
boolean ans1=p1==p2;
boolean ans2=p1.name.equals(p2.name);
System.out.print(ans1 + ":" + ans2);
}
}

What is the result?

A. true:true

B. true:false

C. false:true

D. false:false

 

정답: C

해설:

p1과 p2는 Product 객체를 새로 생성했으니 주소값이 다를 것이고 주소값 비교 p1==p2를 하니 false가 될것이다.

그리고 문자열 비교 메소드인 equals 를 사용하니 동일하게 "Pen" 이기 때문에 true 이다.

참고로 String 클래스의 equals 메소드에 대한 API 설명이다.

boolean java.lang.String.equals(Object anObject)

  • equalspublic boolean equals(Object anObject)

    Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

    Overrides:equals in class ObjectParameters:anObject - The object to compare this String againstReturns:true if the given object represents a String equivalent to this string, false otherwiseSee Also:compareTo(String), equalsIgnoreCase(String)

 

참고로 Product 클래스는 public 으로 되어 있어 어디서는 사용되야 하기 때문에 그 자신의 이름 즉, Public.java 로 만들어져 있어야 한다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함